Customizing object response using jersy / JAX-RS REST

I have a current implementation of object and REST API using Jersey / JAX-RS.

Object / Bean:

@XmlRootElement(name = "MyEntry")
@XmlType(propOrder = {"key", "value"})
public class MyEntry {

  private String key;
  private String value;

  public MyEntry() {
  }

  public MyEntry(String key, String value) {
    this.key = key;
    this.value = value;
  }

  @XmlElement
  public String getKey() {
    return key;
  }

  public void setKey(String key) {
    this.key = key;
  }

  @XmlElement
  public String getValue() {
    return value;
  }

  public void setValue(String value) {
    this.value = value;
  }
}

      

There is now a higher level object that will be my final answer.

public class MyResponse {

  protected String id;
  protected String department;
  protected List<MyEntry> myEntries;

  public String getDepartment() {
      return department;
  }

  public void setDepartment(String department) {
      this.department = department;
  }

  public List<MyEntry> getMyEntries() {
    return myEntries;
  }

  public void setMyEntry(List<MyEntry> myEntries) {
    this.myEntries = myEntries;
  }

  public String getId() {
    return id;
  }

  public void setId(String id) {
    this.id = id;
  }
}

      

My API call looks like this:

@GET
@Path(/v1/myresource)
public MyResponse getMyResource(...... list of parameters ....) {}

      

Now the result looks like below

{
   id: "myid",
   department: "mydepartment",
   myentries: [
     {
        key: "key1",
        value: "value1"
     },
     {
        key: "key2",
        value: "value2"
     },
     {
        key: "key3",
        value: "value3"
     }
   ]
}

      

However, I am trying to get the output as shown below:

{
   id: "myid",
   department: "mydepartment",
   myentries: [
       key1: "value1"
       key2: "value2"
       key3: "value3"
  ]
}

      

Any suggestions would be very helpful.

==== Update ==== After adding the XmlAdapter suggestion everything works. However, one more thing - I have another place where I have to use ObjectMapper to deserialize the request input to the Department class

private MyResponse createResponse(String requestBody...) throws Exception {
    ObjectMapper mapper = new ObjectMapper();
    MyResponse response = null;
    try {
        response = mapper.readValue(requestBody, MyResponse.class);
    } catch (Exception ex) {
        //
    }
}

      

I am getting this error Unable to deserialize java.util.ArrayList instance from START_OBJECT token \ at [Source: java.io.StringReader@20fcc207 ; line: 8, column: 37] (via link chain: com.apigee.apimodel.repo.persistence.beans.MyResponse [\ "myEntries \"]

Is there a way to configure the ObjectMapper to identify @XmlJavaTypeAdapter (MyEntryAdapter.class) when reading a value into an object?

+3


source to share


1 answer


First, this is not valid JSON

myentries: [
    key1: "value1"
    key2: "value2"
    key3: "value3"
]

      

Key / Values ​​must be contained in s JSON object

myentries: {
    key1: "value1"
    key2: "value2"
    key3: "value3"
}

      

That being said, one can convert to Java Map

. But you want List<MyEntry>

. For this we can use XmlAdapter

to convert Map<String, String>

to List<MyEntry>

. It would be something like

public class MyEntryAdapter extends XmlAdapter<HashMap<String, String>, List<MyEntry>> {

    @Override
    public List<MyEntry> unmarshal(HashMap<String, String> map) throws Exception {
        List<MyEntry> entries = new ArrayList<>();
        for (Map.Entry<String, String> entry: map.entrySet()) {
            MyEntry myEntry = new MyEntry();
            myEntry.setKey(entry.getKey());
            myEntry.setValue(entry.getValue());
            entries.add(myEntry);
        }
        return entries;
    }

    @Override
    public HashMap<String, String> marshal(List<MyEntry> entries) throws Exception {
        HashMap<String, String> map = new HashMap<>();
        for (MyEntry entry: entries) {
            map.put(entry.getKey(), entry.getValue());
        }
        return map;
    }
}

      

Then we just annotate the attribute myEntries

@XmlJavaTypeAdapter

@XmlRootElement
public class MyResponse {
    ...
    protected List<MyEntry> myEntries;
    ...
    @XmlJavaTypeAdapter(MyEntryAdapter.class)
    public List<MyEntry> getMyEntries() {
        return myEntries;
    }
    ...
}

      

Here's an example of a test run with GET and POST

Resource class

@Path("/test")
public class TestResource {

    @GET
    @Produces(MediaType.APPLICATION_JSON)
    public Response getResponse() {
        MyResponse response = new MyResponse();
        response.setId("1");
        response.setDepartment("Hard Knocks");
        List<MyEntry> entries = new ArrayList<>();
        MyEntry entry = new MyEntry();
        entry.setKey("key1");
        entry.setValue("value1");
        entries.add(entry);
        entry = new MyEntry();
        entry.setKey("key2");
        entry.setValue("valu2");
        entries.add(entry);
        response.setMyEntry(entries);
        return Response.ok(response).build();
    }

    @POST
    @Consumes(MediaType.APPLICATION_JSON)
    public Response post(MyResponse response) {
        System.out.println("id: " + response.getId());
        System.out.println("Department: " + response.getDepartment());
        System.out.println("MyEntrys: ");
        for (MyEntry entry : response.getMyEntries()) {
            System.out.println(entry);
        }
        return Response.ok().build();
    }
}

      

Test case

@Test
public void testGetIt() throws Exception {
    target = target.path("test");

    Response response = target.request().accept(MediaType.APPLICATION_JSON).get();
    String jsonResponse = response.readEntity(String.class);
    System.out.println(jsonResponse);

    String jsonPost = "{\n"
            + "    \"department\": \"Hard Knocks\",\n"
            + "    \"id\": \"1\",\n"
            + "    \"myEntries\": {\n"
            + "        \"key1\": \"value1\",\n"
            + "        \"key2\": \"valu2\"\n"
            + "    }\n"
            + "}";
    response = target.request().post(Entity.json(jsonPost));

    response.close();
}

      



Result from GET

{
    "id": "1",
    "department": "Hard Knocks",
    "myEntries": {
        "key1": "value1",
        "key2": "valu2"
    }
}

      

Result from POST (override toString in MyEntry)

id: 1
Department: Hard Knocks
MyEntrys: 
MyEntry{key=key1, value=value1}
MyEntry{key=key2, value=valu2}

      


Note:

I have tested two different providers. The one that gave the above result was

<dependency>
    <groupId>org.glassfish.jersey.media</groupId>
    <artifactId>jersey-media-json-jackson</artifactId>
    <version>2.13</version>
</dependency>

      

I have also tried it with MOXy provider

<dependency>
    <groupId>org.glassfish.jersey.media</groupId>
    <artifactId>jersey-media-moxy</artifactId>
    <version>2.13</version>
</dependency>

      

But this is the result I got (with GET, the card is printed as a string, and POST is returned with 0 MyEntrys)

{
    "department": "Hard Knocks",
    "id": "1",
    "myEntries": "{key1=value1, key2=valu2}"
}

      

Not sure why MOXy doesn't work in this case.

+3


source







All Articles