alibaba.fastjson.JSONObject中JSON转对象,对象中有其他对象属性
alibaba.fastjson.JSONObject中JSON转对象,对象中有其他对象属性时,满足以下几个条件也能使用JSONObject.parseObject()转换
1. 子对象的对象名,要和JSON中的字段名一致,否则会爆NPE
2. JSON串中的子对象字段需要在使用大括号{}包裹
一个简单的DEMO
import com.alibaba.fastjson.JSONObject;
public class Test {
public static class One {
private int id;
private int age;
private Two two;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public Two getTwo() {
return two;
}
public void setTwo(Two two) {
this.two = two;
}
@Override
public String toString() {
return "One{" +
"id=" + id +
", age=" + age +
", two=" + two +
'}';
}
}
public static class Two {
private String name;
private int height;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getHeight() {
return height;
}
public void setHeight(int height) {
this.height = height;
}
@Override
public String toString() {
return "Two{" +
"name='" + name + '\'' +
", height=" + height +
'}';
}
}
public static void main(String[] args) {
String ret = "{\"id\": 1,\n" +
" \"age\": 25,\n" +
" \"two\": {\n" +
" \"name\": \"John\",\n" +
" \"height\": 180\n" +
" }}";
One one = JSONObject.parseObject(ret, One.class);
Two two = one.getTwo();
System.out.println(one.toString());
System.out.println(two.toString());
}
}
ret
One{id=1, age=25, two=Two{name='John', height=180}}
Two{name='John', height=180}
DEMO说明
{
"id": 1,
"age": 25,
"two": {
"name": "John",
"height": 180
}
}
JSON串的格式,对应了子对象two,并将子对象的属性使用{}
alibaba.fastjson.JSONObject下的方法是需要实体类有getter、setter方法的,否则会将属性设为默认值。
把getter setter方法删除得到结果如下:
One{id=0, age=0, two=null}
fastjson常用方法
//对于一个请求体,json格式,封装的过程
JSONObject jsonObject = new JSONObject();
jsonObject.put("key1", value1);
jsonObject.put("key2", value2);
jsonObject.put("key3", value3);
//若有子对象,多封装一层
JSONObject subJson= new JSONObject();
subJson.put("key41", value41);
subJson.put("key42", value42);
jsonObject.put("key4", subJson);
//得到json串
String requestBody = jsonObject.toJSONString();
---------------------------
{
"key1": value1,
"key2": value2,
"key3": value3,
"key4": {
"key41": value41,
"key42": value42
}
}
------------String转为JSONObject---------------
JSONObject jsonObject = JSON.parseObject(JSON);
String v1 = jsonObject.getString("key1");//getxxx() 不同的xxx方法能得到xxx类型
----------String的JSON串转对象,相同对应‘key-属性‘会赋值---------
Object object = JSONObject.parseObject(Json, Object.class);