简体   繁体   中英

Jersey 2.0 HashMap conversion to/from Json

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!

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}

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM