引入依赖包:
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.47</version>
</dependency>
JSON:fastJson的解析器,用于JSON格式字符串与JSON对象及javaBean之间的转换。
JSONObject:fastJson提供的json对象。
JSONObject:fastJson提供的json对象。
JAVA对象转JSON字符串
String s = JSON.toJSONString(entity);
JSON字符串转JSON对象
JSONObject jsonObject = JSON.parseObject(jsonString);
JSON字符串转JAVA简单对象
Entiity entity= JSON.parseObject(jsonString, Entity.class);
String——>>>JSONObject
String st = "{name:Tim,age:25,sex:male}";
JSONObject jsonObj= JSONObject.parseObject(st);
String——>>>JSONArray
String st = "[{name:Tim,age:25,sex:male},{name:Tom,age:28,sex:male},{name:Lily,age:15,sex:female}]";
JSONArray JsonArray = JSONArray.parseArray(st);
JSONArray——>>>Object
for(int i;i<JsonArray .size();i++){
Object obj = JsonArray .get(i);
}
Object——>>>JSONObject
JSONObject jsonObj = (JSONObject) JSONObject.toJSON(obj);
//JSONObject jsObj = JSONObject.parseObject(obj.toString());
JSONObject——>>>JSONArray
JSONObject JsonObject= {info:
[
{
name:Tim,
age:25,
sex:male
},{
name:Tom,
age:28,
sex:male
},{
name:Lily,
age:15,
sex:female
}
]
};
JSONArry JsonArry = JsonObject.get("info");
JSONObject 添加值
JSONObject jsObj;
jsObj.put(String key,Object object);
JSONArray 添加 JSONObject
JSONArray resultArray = new JSONArray();
resultArray.add(int index,Object element);
//or resultArray.add(Object element);