问题如下
下面是一个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; } }
原文地址:https://www.cnblogs.com/-beyond/p/12670492.html
时间: 2024-10-09 20:02:09