0
我正在使用第三方库(准确地说是Elasticsearch 2.3.3),它已经将给定的JSON结构解析为我的Map<String,Object>
实例,我想创建一个类的对象原本是整理成JSON的一个实例:Jackson JSON:将属性的Map <String,Object>解组为原始类
- 编组站:
MarshallableObject
→marshalled_object.json
- 解组:
marshalled_object.json
→Map<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);
});
}
}
}
是的,我看到'org.elasticsearch.search.SearchHit.getSourceAsString()'方法,并希望有可能重新使用地图。我猜想可能不是...... – errantlinguist
**来自遥远未来的注意:**由于似乎不可能使用'SearchHit'类创建的'Map',所以最好使用'SearchHit.sourceRef()'for因为'sourceAsString()'实际上调用了前面的方法,但实际上对sourceRef()的结果做了自己的JSON处理来创建一个字符串,所以解组编码。 – errantlinguist