基本规范
#####Object转JSON字符串:
String jsonStr = JSONObject.toJSONString(object);
#####JSON字符串转JSONObject:
JSONObject jsonObject = JSONObjcet.parseObject(jsonStr);
#####JSON字符串转Object对象
T t = JSON.parseObject(jsonStr,T.class);
#####将无泛型集合转为指定类型集合
String jsonString = JSONObject.toJSONString(list);
List<T> list = JSON.parseArray(jsonString,T.class);
-----注:JSON字符串是有格式要求的,必须为键值对形式,不是任意的字符串。-----
原文链接:https://blog.csdn.net/qq_29468573/article/details/82190005
在springboot中使用
@ResponseBody
@RequestMapping(value = "/deleteUser", method = RequestMethod.POST)
public CommonResponse deleteUser(HttpServletRequest request) {
//将json字符串解析成JSONObject 对象
JSONObject jsonObject = JSONObject.parseObject(request);
//获取json里面的数据
Integer id = jsonObject.getInteger("id");
Integer companyId = jsonObject.getInteger("companyId");
//再进行下一步处理
}
测试示例
引用于 https://www.jianshu.com/p/a63b57a766c9
package test;
import java.util.Iterator;
import org.junit.Test;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
public class FastJsonDemo {
@Test
public void testFastJson() {
// json格式的字符串
String jsonStr = "{\r\n" + "\"name\":\"jarWorker\",\r\n" + "\"sex\":\"男\",\r\n" + "\"age\":26,\r\n"
+ "\"love\":[{\"hobby\":\"足球\",\"color\":\"White\"},{\"hobby\":\"篮球\",\"color\":\"Brown\"},{\"hobby\":\"简书\",\"color\":\"Yellow\"}],\r\n"
+ "\"goodAt\":\"Java\"\r\n" + "}";
Object jsonObj = JSON.toJSON(jsonStr);
System.out.println("toJSON>>>" + jsonObj);
System.out.println("——————————————————————————————————");
Object jsonParse = JSON.parse(jsonStr);
System.out.println("parse>>>" + jsonParse);
System.out.println("——————————————————————————————————");
String jsonString = JSON.toJSONString(jsonStr);
System.out.println("jsonString>>>" + jsonString);
System.out.println("——————————————————————————————————");
JSONObject jsonObject = JSON.parseObject(jsonStr);// json对象
String name = jsonObject.getString("name");
String sex = jsonObject.getString("sex");
String age = jsonObject.getString("age");
String goodAt = jsonObject.getString("goodAt");
System.out.println("name====" + name);
System.out.println("sex====" + sex);
System.out.println("age====" + age);
System.out.println("goodAt====" + goodAt);
String love = jsonObject.getString("love");
JSONArray jsonArray = JSON.parseArray(love);// json数组对象
String ArrayStr=JSONArray.toJSONString(jsonArray);
System.out.println("ArrayStr====" + ArrayStr);
System.out.println("——————————————————————————————————");
int count = 0;// 测试用
Iterator<Object> it = jsonArray.iterator();// 使用Iterator迭代器
while (it.hasNext()) {
// 遍历数组
JSONObject arrayObj = (JSONObject) it.next();// JSONArray中是很多个JSONObject对象
String hobby = arrayObj.getString("hobby");
String color = arrayObj.getString("color");
count++;
System.out.println("hobby>>>" + hobby);
System.out.println("color>>>" + color);
System.out.println("------------------------------------");
}
System.out.println("数组中的JSONObject个数:" + count);
}
}