如何使用Jackson解析不合格的JSON数组? [英] How can I parse an unqualified JSON array using Jackson?

查看:258
本文介绍了如何使用Jackson解析不合格的JSON数组?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以,我正在访问第三方API并且它给了我这个JSON对象,但是我有一段时间试图找到一种优雅的方法来使用Jackson解析资源子对象。

So, I am accessing a third-party API and it's giving me this JSON object, but I'm having a whale of a time trying to find an elegant way to parse the resources sub-object using Jackson.

我假设我必须编写一个自定义反序列化器,但我想知道是否还有另一种方式......

I'm assuming I have to write a custom deserializer, though I'm wondering if there's another way...

{
    "somekey": "somevalue",
    "resources": [
        "list",
        [
            {
                "@type": "com.yada.Yada",
                "resource": {
                    "@type": "ServiceObjectReference",
                    "id": "emp1234",
                    "displayName": "Bob Smith"
                },
                "type": "TYPE_PERSON",
                "resourceType": 200
            },
           {
                "@type": "com.yada.Yada",
                "resource": {
                    "@type": "ServiceObjectReference",
                    "id": "emp1235",
                    "displayName": "Sue Smith"
                },
                "type": "TYPE_PERSON",
                "resourceType": 200
            }
       ]
   ]
}


推荐答案

由于资源的值是具有不同对象类型的数组,因此您可能不希望使用POJO进行映射。不确定自定义反序列化器的实现,但您可能希望使用ObjectMapper#readTree方法,而不是根据类型读取节点值

Since the value of resources is an array with different object type, probably you don't want to use POJO for the mapping. Not sure about your implementation of custom deserializer, but you might want to use ObjectMapper#readTree method, than read the node value based on its type

ObjectMapper mapper = new ObjectMapper();
JsonNode rootNode = mapper.readTree(your_json_input);

JsnoNode resourcesNode = rootNode.path("resources");

for (JsonNode resourceNode : resourcesNode ) {
    if (resourceNode.isObject()) {
        // the node is an object, you could do POJO mapping now or keep using path() method to go deeper
    } else {
        // simply get the String value
        String list = resourceNode.getTextValue();
    }
}

这篇关于如何使用Jackson解析不合格的JSON数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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