JSON,JSON字符串,java对象之间互转

以下所有内容使用的是fastjson
JSONObject是继承于JSON,下面JSONObject调用的方法都来自于JSON类。

json字符串转json对象或者java对象使用的都是 JSON.parseObject() 方法
json对象和java对象转成json字符串使用的嗾使 JSON.toJSONString() 方法
java对象转json对象需要强转 JSON.toJSON()
json对象转java对象 JSON.toJavaObject()

public class TestFastJson {
    
    
    //json字符串-简单对象型
    private static final String  JSON_OBJ_STR = "{\"studentName\":\"lily\",\"studentAge\":12}";
    //json字符串-数组类型
    private static final String  JSON_ARRAY_STR = "[{\"studentName\":\"lily\",\"studentAge\":12},{\"studentName\":\"lucy\",\"studentAge\":15}]";
    //复杂格式json字符串
    private static final String  COMPLEX_JSON_STR = "{\"teacherName\":\"crystall\",\"teacherAge\":27,\"course\":{\"courseName\":\"english\",\"code\":1270},\"students\":[{\"studentName\":\"lily\",\"studentAge\":12},{\"studentName\":\"lucy\",\"studentAge\":15}]}";

    public static void main(String[] args) {
    
    
		System.out.println("json字符串转json对象或者json数组");
        JSONObject jsonObject1 = JSON.parseObject(JSON_OBJ_STR);
        JSONObject jsonObject = JSONObject.parseObject(JSON_OBJ_STR);
        
		JSONArray jsonObject2 = JSON.parseArray(JSON_ARRAY_STR);
        JSONArray jsonObject4 = JSONObject.parseArray(JSON_ARRAY_STR);
        
		JSONObject jsonObject3 = JSON.parseObject(COMPLEX_JSON_STR);
        JSONObject jsonObject5 = JSONObject.parseObject(COMPLEX_JSON_STR);

		System.out.println("json字符串转java对象或集合");
        Student student = JSON.parseObject(JSON_OBJ_STR, Student.class);
        Student student2 = JSON.parseObject(JSON_OBJ_STR, new TypeReference<Student>(){
    
    });
        List<Student> students = JSON.parseObject(JSON_ARRAY_STR, new TypeReference<List<Student>>() {
    
    });
		System.out.println("=================================");
	
		System.out.println("java对象转json对象");
		JSONObject o = (JSONObject) JSONObject.toJSON(student2);
		System.out.println("java对象转json字符串");
		String s = JSONObject.toJSONString(student2);
		System.out.println("=================================");
		
		System.out.println("json对象转json字符串");
		String s1 = JSONObject.toJSONString(o);
		System.out.println("json对象转java对象");
		Student s2 = JSON.toJavaObject(o, Student.class);

	}
}
 

在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/ybsgsg/article/details/123349099