0

I have created a simple POST REST webservice that uses a composite object called Track that contians a HashMap inside it. However when I test it using POSTMAN and pass JSON string then it doesnt deserialize the hashmap present in the json to the TestObj POJO defined below When I debug the code I see the map is empty, other values are populated.

Here is the code

//Java class definitions

@XmlRootElement
public class Track {
String title;
String singer;
TestObj test;

public TestObj getTest() {
    return test;
}

public void setTest(TestObj test) {
    this.test = test;
}

public String getTitle() {
    return title;
}

public void setTitle(String title) {
    this.title = title;
}

public String getSinger() {
    return singer;
}

public void setSinger(String singer) {
    this.singer = singer;
}

@Override
public String toString() {
    return "Track [title=" + title + ", singer=" + singer + "]";
}

}

public class TestObj {
String name;
Map<String,String> testMap;

public Map<String, String> getTestMap() {
    return testMap;
}

public void setTestMap(Map<String, String> testMap) {
    this.testMap = testMap;
}

public String getName() {
    return name;
}

public void setName(String name) {
    this.name = name;
}
}

// input JSON string that I pass from POSTMAN

{ "title": "Enter Sandman", "singer": "Metallica", "test": { "name": "John", "testMap": { "1": "1", "2": "2" } } }

My REST POST Service

@POST
@Path("/posttrack")
@Consumes(MediaType.APPLICATION_JSON)
public Response createTrackInJSON(Track track) {

    String result = "Track  " + track;
    return Response.status(201).entity(result).build();

}
user3247376
  • 205
  • 1
  • 4
  • 13

2 Answers2

0

What is the exact failure? I guess it's the typical error, that it cannot deserialize an interface, you have to define exactly what implementation it there in the JSON, cf. https://stackoverflow.com/a/14402856/5471574

D. Kovács
  • 1,232
  • 13
  • 25
  • There is no failure but when I debug I see that my testMap in the TestObj POJO is empty. It shud contain the values that I passed in the input json – user3247376 Jul 13 '17 at 08:55
0

Update jersey version to 1.19 and added the below in web.xml to skip use of @XmlRootElement

   <init-param>
        <param-name>com.sun.jersey.api.json.POJOMappingFeature</param-name>
        <param-value>true</param-value>
    </init-param>

<dependency>
  <groupId>com.sun.jersey</groupId>
  <artifactId>jersey-server</artifactId>
  <version>1.19</version>
</dependency>

<dependency>
  <groupId>com.sun.jersey</groupId>
  <artifactId>jersey-bundle</artifactId>
  <version>1.19</version>
</dependency>

<dependency>
  <groupId>com.sun.jersey</groupId>
  <artifactId>jersey-json</artifactId>
  <version>1.19</version>
</dependency>

Older versions of jersey didn't support unmarshalling of hashmap

user3247376
  • 205
  • 1
  • 4
  • 13