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);

	}
}
 

在这里插入图片描述

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值