欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

Java中json数据的组装和解析

程序员文章站 2022-05-08 19:13:38
...

1、json组装

// json数据
{
    "userName": "xxx",
    "email": "xxxx",
    "phone": 13588888888,
    "level": 1,
    "timestamp": 1616296271000,
    "parentId": 2,
    "appInfo": [
        {
            "appId": "app1xxx",
            "sign": "sign1xxx"
        },
        {
            "appId": "app2xxx",
            "sign": "sign2xxx"
        }
    ]
}

// java代码
import cn.hutool.json.JSONObject;

HashMap<String, Object> outHashMap = new HashMap<>();

        outHashMap.put("userName", user.getUserName());
        outHashMap.put("email", user.getEmail());
        outHashMap.put("phone", user.getMobile());
        outHashMap.put("level", 1);
        outHashMap.put("timestamp", currentTimeMillis);
        outHashMap.put("parentId", userLevel.getGetuiId());

        ArrayList<HashMap<String, String>> hashMaps = new ArrayList<>();
        HashMap<String, String> smallHashMap = new HashMap<>();
        smallHashMap.put("appId", geTuiConfig.getAppId());
        smallHashMap.put("sign","sign"));
        hashMaps.add(smallHashMap);

        outHashMap.put("appInfo", hashMaps);

        JSONObject addUserJsonParam = new JSONObject(outHashMap);

2、json解析

// json数据
{
    "code": 0,
    "data": [
        {
            "ip": "10.200.77.167",
            "sysname": "hybase",
            "itemlist": [
                {
                    "unit": "",
                    "name": "节点状态",
                    "value": "on",
                    "key": "server_status"
                },
                {
                    "unit": "%",
                    "name": "CPU使用率",
                    "value": "1.87",
                    "key": "cpu_usage"
                }
            ],
            "id": "hybase1"
        }
    ],
    "message": "成功"
}

// java代码
String s = HttpUtil.get("http://127.0.0.1:6666/public/status");
        JSONObject jsonObject = new JSONObject(s);
        JSONArray data = jsonObject.getJSONArray("data");
        // 这里的JSON是import com.alibaba.fastjson.JSON;
        List<Status> statusList = JSON.parseArray(data.toString(), Status.class);
        for (Status status : statusList) {
            HybaseStatus hybaseStatus = new HybaseStatus();
            hybaseStatus.setIp(status.getIp());
            hybaseStatus.setSysname(status.getSysname());
            hybaseStatus.setHybase_id(status.getId());
            for (Item item : status.getItemlist()) {
                hybaseStatus.setName(item.getName());
                hybaseStatus.setHybase_key(item.getKey());
                hybaseStatus.setHybase_value(item.getValue());
                hybaseStatus.setUnit(item.getUnit());
                hybaseStatus.setCreate_time(DateUtil.format(new Date(), "yyyy-MM-dd HH:mm:ss"));
                statusService.InsertData(hybaseStatus);
            }


        }
相关标签: Java json java