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


    问题如下

      下面是一个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;
        }
    }
    

      

      

  • 相关阅读:
    python学习之计算机基础详解
    python学习笔记-day03
    名称空间与作用域
    函数参数的应用
    day14
    day13
    函数的基本使用
    day12
    day 09
    文件操作
  • 原文地址:https://www.cnblogs.com/-beyond/p/12670492.html
Copyright © 2020-2023  润新知