码迷,mamicode.com
首页 > Web开发 > 详细

如何解析字段名称不确定的json字符串

时间:2020-04-10 00:49:46      阅读:229      评论:0      收藏:0      [点我收藏+]

标签:字段   import   打印   lombok   RoCE   exce   integer   stack   inner   

问题如下

  下面是一个json字符串,有其他系统提交过来的,当前需要对该json字符串进行解析,需要注意的是,外层的key是不确定的(随机的字符串),但是内层的value字段名称和类型都可以确定。

{
    "fa490c67-bdb2-4ddd-810d-894e9ceeba0e":{
        "top":191,
        "left":55,
        "process_to":[
            "bd7c788d-9d2f-48da-80ad-726edb8dffb1"
        ]
    },
    "bd7c788d-9d2f-48da-80ad-726edb8dffb1":{
        "top":171,
        "left":281,
        "process_to":[

        ]
    }
}

  

解析方案

package cn.ganlixin.test;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.Data;
import org.junit.Test;

import java.util.Iterator;
import java.util.List;
import java.util.Map;

public class JsonUtilsTest {

    @Test
    public void test() throws JsonProcessingException {
        String s = "{\"fa490c67-bdb2-4ddd-810d-894e9ceeba0e\":{\"top\":191,\"left\":55,\"process_to\":[\"bd7c788d-9d2f-48da-80ad-726edb8dffb1\"]},\"bd7c788d-9d2f-48da-80ad-726edb8dffb1\":{\"top\":171,\"left\":281,\"process_to\":[]}}";

        ObjectMapper objectMapper = new ObjectMapper();
        final JsonNode jsonNode = objectMapper.readTree(s);

        // 进行迭代
        final Iterator<Map.Entry<String, JsonNode>> fields = jsonNode.fields();
        fields.forEachRemaining(item -> {
            MyOutEntity myOutEntity = new MyOutEntity();
            myOutEntity.setKey(item.getKey());
            try {
                MyInnerEntity myInnerEntity = objectMapper.readValue(item.getValue().toString(), MyInnerEntity.class);
                myOutEntity.setMyInnerEntity(myInnerEntity);
            } catch (JsonProcessingException e) {
                e.printStackTrace();
            }

            // 打印解析完的一个对象
            System.out.println(myOutEntity);
        });
        
        // JsonUtilsTest.MyOutEntity(key=fa490c67-bdb2-4ddd-810d-894e9ceeba0e, myInnerEntity=JsonUtilsTest.MyInnerEntity(top=191, left=55, process_to=[bd7c788d-9d2f-48da-80ad-726edb8dffb1]))
        //JsonUtilsTest.MyOutEntity(key=bd7c788d-9d2f-48da-80ad-726edb8dffb1, myInnerEntity=JsonUtilsTest.MyInnerEntity(top=171, left=281, process_to=[]))
    }

    @Data
    private static class MyOutEntity {
        private String key;
        private MyInnerEntity myInnerEntity;
    }

    @Data
    private static class MyInnerEntity {
        private Integer top;
        private Integer left;
        private List<String> process_to;
    }
}

  

  

如何解析字段名称不确定的json字符串

标签:字段   import   打印   lombok   RoCE   exce   integer   stack   inner   

原文地址:https://www.cnblogs.com/-beyond/p/12670492.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!