fastjson json对象 java对象 和 string 之间的转换
所属分类 fastjson
浏览量 1193
json对象 java对象 和 string 之间的转换
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
import dyyx.dto.Pet;
public class FastjsonTransTest {
public static void main(String[] args) throws Exception {
System.out.println("hello,FastjsonTransTest," + new Date());
Pet pet1 = new Pet("cat",1,new Date());
Pet pet2 = new Pet("tiger",3,new Date());
List pets = new ArrayList();
pets.add(pet1);
pets.add(pet2);
// Java 对象转string
String petstr = JSON.toJSONString(pet1);
String petsstr = JSON.toJSONString(pets);
System.out.println(petstr);
System.out.println(petsstr);
// string 转 json对象
JSONObject pet1JsonObject = JSON.parseObject(petstr);
// java.lang.ClassCastException: com.alibaba.fastjson.JSONArray cannot be cast to com.alibaba.fastjson.JSONObject
// JSONObject petsJsonObject = JSON.parseObject(petsstr);
JSONArray petsJsonArray = JSON.parseArray(petsstr);
// json对象 转 string
System.out.println(JSON.toJSONString(pet1JsonObject));
System.out.println(JSON.toJSONString(petsJsonArray));
// string 转 java对象
Pet pet1JavaObject = JSON.parseObject(petstr, Pet.class);
System.out.println(pet1JavaObject);
List petsJavaObject = JSON.parseObject(petsstr, List.class);
// JSONObject
for(Object item:petsJavaObject){
System.out.println(item+","+item.getClass());
}
List petsJavaObject2 = JSON.parseObject(petsstr, new TypeReference>() {});
for(Pet item:petsJavaObject2){
System.out.println(item+","+item.getClass());
}
// json对象 转 java对象
// 需要默认构造函数
Pet pet1JavaObject2 = pet1JsonObject.toJavaObject(Pet.class);
System.out.println(pet1JavaObject2);
List petsJavaObject3 = petsJsonArray.toJavaObject(new TypeReference>() {});
for(Pet item:petsJavaObject3){
System.out.println(item+"||"+item.getClass());
}
}
}
完整代码
https://gitee.com/dyyx/demos/blob/master/jackson/src/test/java/dyyx/FastjsonTransTest.java
上一篇
下一篇
fastjson使用实例
工程师文化
JSON简介
15条简单的职场规则
fastjson为什么这么多安全漏洞
递归与尾递归java实例