【问题标题】:ObjectMapper readValueObjectMapper 读取值
【发布时间】:2017-03-09 09:33:24
【问题描述】:

我加载了一个资源文件 json 用文本格式

{
    "sources": [{
            "prop1": "1",
            "prop2": "2"

        },
        {
            "prop1": "1",
            "prop2": "2"

        },
    ],
    "redirection": [{
            "prop1": "1",
            "prop2": "2"

        }
    ]
}

我有一个具有此属性 prop1 和 prop2 的类

我想用 ObjectMapper 恢复一个列表类。什么方法?

此代码不起作用....

 Map<String, Object> mp =  mapper.readValue(jsonResource.getInputStream(),new TypeReference<Map<String, Object>>() {});
String sourceText= new ObjectMapper().readTree(jsonResource.getInputStream()).get("sources").asText();

 mapper.readValue(sourceText, new TypeReference<List<MyClass>>(){});

感谢您的帮助

【问题讨论】:

    标签: java spring objectmapper


    【解决方案1】:

    在你的情况下,我会写一个自定义的JsonDeserializer。还没有真正测试过代码,但我认为这个想法很明确:

        final MyClassDeserializer myClassDeserializer = new MyClassDeserializer();
        final SimpleModule deserializerModule = new SimpleModule();
        deserializerModule.addDeserializer(MyClass.class, myClassDeserializer);
    
        final ObjectMapper mapper = new ObjectMapper();
        mapper.registerModule(deserializerModule);
    

    还有JsonDeserializer的代码:

        public class MyClassDeserializer extends JsonDeserializer<MyClass> {
    
        @Override
        public MyClass deserialize(final JsonParser jsonParser, final DeserializationContext context)
                throws IOException {
            final JsonNode node = jsonParser.getCodec().readTree(jsonParser);
            final JsonNode sourcesNode = node.get("sources");
            if(node.isArray()) {
                final ArrayNode arrayNode = (ArrayNode) node;
                final Iterable<JsonNode> nodes = arrayNode::elements;
                final Set<Source> set = StreamSupport.stream(nodes.spliterator(), false)
                        .map(mapper)
                        .collect(Collectors.toSet());
                ...
            }
    
            ...
        }
    

    【讨论】:

    • 我什么都不懂,但我会尝试我们不能有文本节点?
    • 你可以有一个文本节点,但它将是一个String。使用我的方法,您只需创建一个我认为更好的 Source 对象。
    【解决方案2】:

    第一件事:您的 JSON 无效。 sources 数组中的第二个对象后面有一个逗号。必须删除。

    第二:我认为你没有为你的结果选择正确的类型。你的 JSON 代表的是一个从字符串映射到对象数组的映射。所以类型应该是Map&lt;String, Props[]&gt; (因为你没有提供你的类的名字,我称之为Props

    考虑到这些因素,您可以使用ObjectMappers getTypeFactory() 方法构造MapType,并使用构造类型反序列化值,如下所示。

    ObjectMapper mapper = new ObjectMapper();
    TypeFactory typeFactory = mapper.getTypeFactory();
    MapType mapType = typeFactory.constructMapType(HashMap.class, String.class, Props[].class);
    Map<String, Props[]> map = mapper.readValue(s, mapType);
    

    【讨论】:

      【解决方案3】:

      我实际上投票支持另一个答案,但这是我的想法,创建类并让杰克逊完成工作:

      public class ResourceTest {
      
          @Test
          public void test1() throws IOException {
              assertTrue(true);
      
              Resource resource = new Resource();
      
              resource.getRedirectrions().add(makeRedirectrion("rprop11", "rprop12"));
              resource.getRedirectrions().add(makeRedirectrion("rprop21", "rprop22"));
      
              resource.getSources().add(makeSource("sprop11","sprop12"));
              resource.getSources().add(makeSource("sprop21","sprop22"));
      
              String json = new ObjectMapper().writeValueAsString(resource);
              System.out.println(json);
      
              Resource resource1 = new ObjectMapper().readValue(json, Resource.class);
              System.out.println(resource1);
          }
      
          private Source makeSource(String prop1, String prop2) {
              Source source = new Source();
              source.setProp1(prop1);
              source.setProp2(prop2);
              return source;
          }
      
          private Redirectrion makeRedirectrion(String prop1, String prop2) {
              Redirectrion redirectrion = new Redirectrion();
              redirectrion.setProp1(prop1);
              redirectrion.setProp2(prop2);
              return redirectrion;
          }
      
      }
      

      输出是:

      {"sources":[{"prop1":"sprop11","prop2":"sprop12"},{"prop1":"sprop21","prop2":"sprop22"}],"redirectrions":[{"prop1":"rprop11","prop2":"rprop12"},{"prop1":"rprop21","prop2":"rprop22"}]}
      Resource{sources=[Source{prop1='sprop11', prop2='sprop12'}, Source{prop1='sprop21', prop2='sprop22'}], redirectrions=[Source{prop1='rprop11', prop2='rprop12'}, Source{prop1='rprop21', prop2='rprop22'}]}
      

      【讨论】:

        猜你喜欢
        • 2016-11-03
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-10-18
        • 1970-01-01
        • 1970-01-01
        • 2019-05-30
        • 2015-01-04
        相关资源
        最近更新 更多