json转对象

json转对象,就是把json串用对象类表示,然后调用new JSONObject().parseObject(json, User.class)方法
如:json串

{
    "id": "10",
    "name": "每特教育",
    "items": [
        {
            "itemId": "20",
            "itemName": "蚂蚁课堂"
        },
        {
            "itemId": "21",
            "itemName": "每特学院"
        }
    ]
}

定义user类,将对象关系包含进去

package com.edu.emple;

import java.util.List;

/**
 * @author shkstart
 * @date 2019/6/10- 20:23
 */
class Item{
    private String itemId;
    private String itemName;

    public String getItemId() {
        return itemId;
    }

    public void setItemId(String itemId) {
        this.itemId = itemId;
    }

    public String getItemName() {
        return itemName;
    }

    public void setItemName(String itemName) {
        this.itemName = itemName;
    }

    @Override
    public String toString() {
        return "Item{" +
                "itemId='" + itemId + '\'' +
                ", itemName='" + itemName + '\'' +
                '}';
    }
}
public class User {
    private String id;
    private String name;
    private List<Item> items;

    public String getId() {
        return id;
    }

    public void setId(String id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public List<Item> getItems() {
        return items;
    }

    public void setItems(List<Item> items) {
        this.items = items;
    }

    @Override
    public String toString() {
        return "User{" +
                "id='" + id + '\'' +
                ", name='" + name + '\'' +
                ", items=" + items +
                '}';
    }
}

测试:

package com.edu.emple;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;

/**
 * @author shkstart
 * @date 2019/6/10- 18:53
 */
public class test001 {
   static String json ="{\"id\":\"10\",\"name\":\"每特教育\",\"items\":[{\"itemId\":\"20\",\"itemName\":\"蚂蚁课堂\"},{\"itemId\":\"21\",\"itemName\":\"每特学院\"}]}";

    public static void main(String[] args) {
        //1.先转换为jsonobject对象
        JSONObject jsonObject = new JSONObject().parseObject(json);
        String id = jsonObject.getString("id");
        System.out.println(id);
        String name = jsonObject.getString("name");
        System.out.println("id:"+id+"name:"+name);
        JSONArray jsonArray =jsonObject.getJSONArray("items");
        for (int i = 0; i < jsonArray.size(); i++) {
            JSONObject jsonObject1 = jsonArray.getJSONObject(i);
            String itemId = jsonObject1.getString("itemId");
            String itemName = jsonObject1.getString("itemName");
            System.out.println("itemId:"+itemId+"----itemName"+itemName);

        }

        //json转对象
        User user = new JSONObject().parseObject(json, User.class);
        System.out.println(user.toString());
    }
}

结果:
json转对象_第1张图片

你可能感兴趣的:(java)