簡體   English   中英

傑克遜JSON:解組地圖 <String,Object> 屬性返回其原始類

[英]Jackson JSON: Unmarshalling a Map<String,Object> of attributes back into its original class

我正在使用第三方庫(確切地說是Elasticsearch 2.3.3 ),該庫已經為我解析了給定的JSON結構成Map<String,Object>實例,並且我想創建該類的實例。最初編組為JSON的對象:

  1. 編組: MarshallableObjectmarshalled_object.json
  2. 解組: marshalled_object.jsonMap<String,Object>MarshallableObject

此外,這是一些示例代碼,說明了邏輯:

import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.Arrays;
import java.util.Map;
import java.util.stream.Stream;

import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.transport.TransportClient;
import org.elasticsearch.common.transport.InetSocketTransportAddress;
import org.elasticsearch.index.query.QueryBuilders;

import com.fasterxml.jackson.databind.ObjectMapper;

public final class AttrMapUnmarshallingTest {

    /**
     * This class was directly used in the process for creating JSON documents indexed by Elasticsearch
     */
    public static final class MarshallableObject {

        public String bar;

        public String foo;

    }

    private static final ObjectMapper OBJECT_MAPPER = new ObjectMapper();

    public static void main(final String[] args) throws UnknownHostException {
        try (final TransportClient client = TransportClient.builder().build().addTransportAddress(new InetSocketTransportAddress(InetAddress.getLoopbackAddress(), 9300))) {

            final SearchResponse response = client.prepareSearch("news").setTypes("article")
                .setQuery(QueryBuilders.matchQuery("text", "advertisement")).execute().actionGet();
        final Stream<Map<String, Object>> attrMaps = Arrays.stream(response.getHits().getHits())
                .map(hit -> hit.sourceAsMap());
        final Stream<MarshallableObject> objs = attrMaps.map(attrMap -> {
            // TODO: Find way of converting attr map into original class
            // which was marshalled into JSON
            // final MarshallableObject obj = OBJECT_MAPPER.read(attrMap);
            });
        }
    }

}

我在SearchHit類上做了一些閱讀,這是我認為可行的方法:

Stream<MarshallableObject> objs = Arrays.stream(response.getHits().getHits())
    .filter(hit->hit.hasSource()) // For some reason source could be null.
    .map(hit->
         OBJECT_MAPPER.readValue(hit.sourceAsString(), 
                                 MarshallableObject.class));

注意:您需要將MarshallableObject類聲明為static才能使讀取工作。 顯然,無法從json字符串重構隱藏的ParentClass$this引用。

祝好運。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM