21.如何将java类对象转化为json字符串

使用阿里巴巴的fastJson

下载链接:

链接: https://pan.baidu.com/s/1dHjLOm1 密码: rr3w

用法如下:

User user = new User();    
user.setAge(18);
user.setUserName("李四");      
String listJson = JSON.toJSONString(user);

 要将一个json对象转化为字符串,只需要toString

 String response = xx
 private JSONObject payInfoJsonObject = new JSONObject(response);
String JSONString = payInfoJsonObject.toString();

 获取键值:

package com.scut.emos.util;

/**
* Created by 蔡木庆 on 2018/2/6.
*/
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
public class JsonTest {
public static void main(String args[]){
String json="{"name":"刘德华","age":35,"some":[{"k1":"v1","k2":"v2"},{"k3":"v3","k4":"v4"}]}";
//解析一层
JSONObject test = JSON.parseObject(json);
System.out.println(test.getString("name"));
//解析json里面嵌套json
JSONArray testA = test.getJSONArray("some");
JSONObject JsonObject0 = testA.getJSONObject(0);
System.out.println(JsonObject0.getString("k1"));
}
}

原文地址:https://www.cnblogs.com/caimuqing/p/8418942.html