Jackson json反序列化映射结构弹性搜索

时间:2015-07-02 11:45:45

标签: jackson

我需要像这样解析一个json文件: 这是我的elasticsearch引擎服务器集合的示例映射文件。

{
    "mappings":
    {
            "documents" :
            {
                    "_all" : {"enabled" : false},
                    "properties" :
                    {
                            "user_id" :
                            {
                                    "type" : "string",
                                    "index" : "not_analyzed",
                                    "store": "no"
                            },
                            "mime_type" :
                            {
                                    "type" : "string",
                                    "index" : "not_analyzed",
                                    "store": "no"
                            },
                            "source" :
                            {
                                    "type" : "string",
                                    "index": "not_analyzed",
                                    "store": "no"
                            }
                    }
            }
    }
}

你可能正在弄清楚架构是这样的:

{
  "mapping":
  {
     "**collection_name**":
     {
       ...,
       "properties":
       {
         "**property_name_1**":
         {
            "type": "string|int|date...",
            ...
         },
         "**property_name_2**":
         {
            "type": "string|int|date...",
            ...
         },
         ...
       }
     }
   }
 }

我需要将这个json映射到类似这样的类:

public class Mapping {

    private String collection;
    private List<Property> properties;

    public Mapping()
    {
        this.collection = null;
        this.properties = new ArrayList<Property>();
    }
    ...

 }

 public class Property
 {
    private String property;
    private String type;
}

我不知道杰克逊怎么做。 请问你能帮帮我吗?谢谢大家。

1 个答案:

答案 0 :(得分:3)

你可以用杰克逊的方式做到这一点:

    ObjectMapper mapper = new ObjectMapper();
    JsonNode rootNode;
    try {
        rootNode = mapper.readValue(jsonText, JsonNode.class);
        JsonNode mappingsNode = rootNode.get("mappings");
        String collectionName = mappingsNode.getFieldNames().next();
        JsonNode collectionNode = mappingsNode.get(collectionName);
        JsonNode propertiesNode = collectionNode.get("properties");
        Iterator<JsonNode> elements = propertiesNode.getElements();
        while (elements.hasNext()) {
            JsonNode propertyNode = (JsonNode) elements.next();
            // get properties one by one

        }
    } catch (IOException e) {
        throw new RuntimeException("error while reading value", e);
    }

代码没有完成它提出的想法。用jackson 1.8.0测试