导入依赖
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>x.x.x</version>
</dependency>
JSONObject 转 JSON 字符串
Java代码:
JSONObject jsonObject = new JSONObject();
jsonObject.put("name", "wjw");
jsonObject.put("age", 22);
jsonObject.put("sex", "男");
jsonObject.put("school", "商职");
String jsonStr = JSONObject.toJSONString(jsonObject);
System.out.println(jsonStr);
执行结果:
{"school":"商职","sex":"男","name":"wjw","age":22}
JSON 字符串 转 JSONObject 对象
Java代码:
String jsonStr = "{\"school\":\"商职\",\"sex\":\"男\",\"name\":\"wjw\",\"age\":22}";
JSONObject jsonObject = JSONObject.parseObject(jsonStr);
System.out.println(jsonObject.getString("name"));
System.out.println(jsonObject.getInteger("age"));
执行结果:
wjw
22
实体类 转 JSONObject对象
创建 Person 对象:
Person person = new Person();
person.setName("wjw");
person.setAge(22);
person.setSex("男");
person.setSchool("商职");
String personStr = JSONObject.toJSONString(person); // 转换为json字符串
System.out.println("personStr:"+personStr);
JSONObject personObject = JSONObject.parseObject(personStr); // 转换为json对象
System.out.println("personObject:"+personObject);
System.out.println("name:"+personObject.getString("name"));
打印结果:
personStr:{"age":22,"name":"wjw","school":"商职","sex":"男"}
personObject:{"school":"商职","sex":"男","name":"wjw","age":22}
name:wjw
参考地址: