ObjectMapper readValue [英] ObjectMapper readValue

查看:1354
本文介绍了ObjectMapper readValue的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我加载资源文件json 文字格式

I load a ressource file json with the text format

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

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

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

        }
    ]
}

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

I have a class with this properties prop1 and prop2

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

I want to recover with ObjectMapper a list class. What the method ?

此代码无效....

 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>>(){});

感谢您的帮助

推荐答案

在您的情况下,我会编写一个自定义的JsonDeserializer.尚未真正测试过代码,但我认为想法很明确:

In your case, I would write a custom JsonDeserializer. Haven't really tested the code, but I think the idea is clear:

    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());
            ...
        }

        ...
    }

这篇关于ObjectMapper readValue的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆