Jersey 2.0 Convert HashMap to / from Json

I have a Json like this provided by a webservice:

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

      

I am using GLasshfish, Netbeans and Jersey tools to consume web resources from WS. According to Jersey features, I am using some Java classes that map Json structure to get transformation in data structures using Jersey (and JAX-RS annotation). For the specified Json package, I created this class:

public class Server 
    {
      ...

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

      

The mapping works fine, except for the "metadata" attribute, which is structured as a map of arbitrary length, and String is both key and value. After this transformation, the result is as follows:

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

      

I have a similar case but no solution. It looks like Jersey 2.0 cannot convert the map's JSL struct attribute to a corresponding Java Data Object (HashMap) struct. There are no exceptions or errors on the server, but the printed json map always contains a "entry": [] and I don't know where it comes from. With other object types or data types, I have no problem (List, int, String ... everything works fine). Can anyone help me? Thanks for the support!

+3


source to share


1 answer


I've tested the JSON string you provided and it works with TypeReference

and ObjectMapper

that return Map<String, Map<String, String>>

according to that 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}

      

0


source







All Articles