3

I've Json like this, that is provided by a webservice:

{ ... "metadata": { "name": "test_server", "server_type": "test", ... }, ... } 

I'm using GLasshfish, Netbeans and Jersey framework to consume web resources from the WS. According to Jersey features, I use some Java classes that map the Json structure, in order to obtain the conversion in data structures using Jersey (and JAX-RS annotation). For the mentioned Json packet I've created this class:

public class Server { ... private Map<String, String> metadata = new HashMap<String, String>(); ... public Server(){} } 

The mapping works all fine, except for the "metadata" attribute, that is structured like a random-lenght map, with a String as both key and value. After that conversion, the result is that:

{ "metadata": { "entry":[] } } 

I've some similar case, but no solution. It seems that Jersey 2.0 isn't able to convert a map stile Json attribute in the corresponding Java data structure Object (HashMap). There aren't no exception or errors on the server, but the printed json map is always containing "entry":[], and I don't know where it comes out from. With other object types or data types I've no problem (List, int, String... all works fine). Can anyone help me? Thanks for support!

1

1 Answer 1

0

I have tested the JSON string that is provided by you and it works using TypeReference and ObjectMapper that return Map<String, Map<String, String>> as per this JSON string.

Here is the code:

String jsonString = "{\"metadata\": {\"name\": \"test_server\",\"server_type\": \"test\"}}"; TypeReference<Map<String, Map<String, String>>> typeRef = new TypeReference<Map<String, Map<String, String>>>() {}; ObjectMapper mapper = new ObjectMapper(); try { Map<String, Map<String, String>> jsonObject = mapper.readValue(jsonString, typeRef); System.out.println(jsonObject.get("metadata")); } catch (Exception e) { System.out.println("Three might be some issue wiht the JSON string"); } 

output:

{name=test_server, server_type=test} 
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks for suggestion, but using the solution provided by you, I will not use the class auto mapping from/to Json in Jersey Moxy style! (In fact your solution is a low based Json processing, based on Jackson library, according to jersey.java.net/documentation/latest/media.html#json)