I'm using a third-party library ( Elasticsearch 2.3.3 , to be exact) which already parses a given JSON structure into a Map<String,Object>
instance for me, and I want to create an instance of the class of the object which was originally marshalled into JSON:
MarshallableObject
→ marshalled_object.json
marshalled_object.json
→ Map<String,Object>
→ MarshallableObject
) Additionally, here is some example code illustrating the logic:
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);
});
}
}
}
I did some reading on the SearchHit
class, and this is what I think may work:
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));
Note: You need to declare the MarshallableObject
class static
to make the reading work. Apparently, the hidden ParentClass$this
reference cannot be reconstructed from the json string.
Good luck.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.