json和对象互转
import com.alibaba.fastjson.JSON;
import java.util.ArrayList;
import java.util.List;
/**
*
*/
public class Json {
public static void main(String[] args) {
//对象转换为json格式
Student student = new Student("张三","男");
String s = JSON.toJSONString(student);
System.out.println(s);
//列表转换为JSON
List<Student> students = new ArrayList<>();
students.add(student);
students.add(new Student("李四","男"));
String s1 = JSON.toJSONString(students);
System.out.println(s1);
//将JSON字符串转换为对象
String jsonStr = "{\"name\":\"张三\",\"sex\":\"男\"}";
Student student1 = JSON.parseObject(jsonStr, Student.class);
System.out.println(student1);
}
}
运行结果
Student student = new Student("张三","男");
//给前端返回数据
//一个空的json对象
JSONObject jsonObject = new JSONObject();
//添加数据
jsonObject.put("status",200);
jsonObject.put("data",student);
//转换为json字符串
String s2 = JSON.toJSONString(jsonObject);
System.out.println(s2);