简体   繁体   English

如何在特定密钥处启动Jackson JSON ObjetMapper?

[英]How can I start a Jackson JSON ObjetMapper at a specific key?

I have a JSON array that I'd like to map that looks like this: 我有一个要映射的JSON数组,如下所示:

{
    "library": [
        {
          "key":"val"
        },
        {
          "key":"val"
        }
    ]
}

Is there a way to parse this using the object mapper starting at the array rather than at the root? 有没有一种使用对象映射器从数组而不是从根开始解析此方法的方法? I know you can do a manual node parse, but I would prefer not to do that if possible. 我知道您可以进行手动节点解析,但是如果可能的话,我不希望这样做。 any help with this would be greatly appreciated. 任何帮助,将不胜感激。

Jackson offers three principal ways to parse json: to a map, to an object, to a jackson node tree. 杰克逊提供了三种解析json的主要方法:映射,对象,杰克逊节点树。 None of these methods offer a way to start from anywhere other than the root. 这些方法都没有提供从根目录以外的任何地方开始的方法。 To start from somewhere other than the root, you need to parse your way to there from the root, which means you need to start parsing from the root! 要从根目录以外的其他地方开始,您需要从根目录解析到那里,这意味着您需要从根目录开始解析! :) :)

That being said, if for example you use mapping to an object, it is very easy to get the array you need out of the object: 话虽如此,例如,如果您使用映射到对象,则很容易从对象中获取所需的数组:

package test;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Map;

import org.codehaus.jackson.JsonParseException;
import org.codehaus.jackson.map.JsonMappingException;
import org.codehaus.jackson.map.ObjectMapper;

public class Test {

    static String json = "{\"library\": [{\"key\":\"val\"},{\"key\":\"val\"}]}";

    static class JsonClass {
        private ArrayList<Map<?,?>> library;

        public ArrayList<Map<?, ?>> getLibrary() {
            return library;
        }

        public void setLibrary(ArrayList<Map<?, ?>> library) {
            this.library = library;
        }
    }

    public static void main(String[] args) 
            throws JsonParseException, JsonMappingException, IOException {

        JsonClass parsed = new ObjectMapper().readValue(json, Test.JsonClass.class);
        System.out.println(parsed.getLibrary());

    }

}

Running this prints: 运行此打印:

[{key=val}, {key=val}]

An alternative would be to use a streaming parser... it can pick any node, without bothering about understanding the whole structure. 一种替代方法是使用流解析器...它可以选择任何节点,而不必担心理解整个结构。 I believe Gson has that. 我相信Gson有。 But in your case it would probably be an overkill to use a streaming parser: it makes sense when the overall structure is complex, you need to process a big stream fast, and are interested in relatively small part of the data. 但是,在您的情况下,使用流解析器可能是一个过大的选择:当整体结构复杂,您需要快速处理大量流并且对相对较小的数据感兴趣时,这是有意义的。 These do not seem to apply to your scenario. 这些似乎不适用于您的方案。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM