FastJSON 转换使用
`package com.yishan.json;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
/**
- @Author yishan
- @Date 2021/9/22 0022 10:43
- @Version 1.0
*/
public class JsonDemo {
public static void main(String[] args) {
//JavaBean2JsonString();
//JsonString2JavaBean();
//JavaBean2JSONObject();
//JsonObject2JavaBean();
}
/**
* javaBean转jsonString---toJSONString()
*/
private static void JavaBean2JsonString() {
List<Student> list = new ArrayList<>();
list.add(new Student("111","yishan","24","上海",new Date()));
list.add(new Student("111","yishan","24","上海",new Date()));
System.out.println(list);
//[Student(id=111, name=yishan, age=24, address=上海, birthday=Wed Sep 22 11:10:16 CST 2021), Student(id=111, name=yishan, age=24, address=上海, birthday=Wed Sep 22 11:10:16 CST 2021)]
String s = JSON.toJSONString(list);
System.out.println(s);
//[{"address":"上海","age":"24","birthday":1632280216104,"id":"111","name":"yishan"},{"address":"上海","age":"24","birthday":1632280216104,"id":"111","name":"yishan"}]
}
/**
* jsonString转javaBean---JSON.parseObject()
* 必须要有默认的无参构造函数,否则反序列化会出错---com.alibaba.fastjson.JSONException: default constructor not found.
*/
private static void JsonString2JavaBean() {
Student student = new Student("111", "yishan", "24", "上海", new Date());
String jsonString = JSON.toJSONString(student);
Student s = JSON.parseObject(jsonString, Student.class);
System.out.println(s);
//Student(id=111, name=yishan, age=24, address=上海, birthday=Wed Sep 22 00:00:00 CST 2021)
}
/**
* javaBean转jsonObject---JSON.toJSON()
*/
private static void JavaBean2JSONObject() {
Student student = new Student("111", "yishan", "24", "上海", new Date());
//方式一:可以先转String,然后转jsonObject,之后通过key获取对应的value
JSONObject jsonObject = JSON.parseObject(JSON.toJSONString(student));
System.out.println(jsonObject.getString("NAME")); //yishan
//方式二:直接转为jsonObject,通过key获取对应的value
JSONObject json = (JSONObject) JSON.toJSON(student);
System.out.println(json.getString("NAME")); //yishan
}
/**
* jsonObject转javaBean---JSON.toJavaObject()
* 必须要有默认的无参构造函数,否则反序列化会出错
*/
private static void JsonObject2JavaBean() {
Student student = new Student("111", "yishan", "24", "上海", new Date());
JSONObject jsonObject = (JSONObject) JSON.toJSON(student);
//方式一:jsonObject转String,然后转为javaBean
Student student1 = JSON.parseObject(jsonObject.toJSONString(), Student.class);
System.out.println(student1);
//方式二:jsonObject直接转javaBean
Student student2 = JSON.toJavaObject(jsonObject, Student.class);
System.out.println(student2);
}
}
`
本文来自博客园,作者:yishan99,转载请注明原文链接:https://www.cnblogs.com/yishan99/p/15323978.html