使用阿里巴巴的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"));
}
}
