I have a current implementation of an object and a 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;
}
}
Now there is a higher level object which is going to be my final response.
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 is as follows :
@GET
@Path(/v1/myresource)
public MyResponse getMyResource(...... list of parameters ....) {}
Now the output 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 an output like below:
{
id: "myid",
department: "mydepartment",
myentries: [
key1: "value1"
key2: "value2"
key3: "value3"
]
}
Any suggestions will be greatly helpful.
==== Update ==== After adding the suggestion of XmlAdapter things are working. However, one more thing is - I have another place where I have to use ObjectMapper to deserialize input request into 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 Can not deserialize instance of java.util.ArrayList out of START_OBJECT token\\ at [Source: java.io.StringReader@20fcc207; line: 8, column: 37] (through reference chain: com.apigee.apimodel.repo.persistence.beans.MyResponse[\\"myEntries\\"]
Is there a way to configure ObjectMapper to identify @XmlJavaTypeAdapter(MyEntryAdapter.class) while reading the value into the object?
First thing, this is not valid JSON
myentries: [
key1: "value1"
key2: "value2"
key3: "value3"
]
Key/Values need to be contained in s JSON object
myentries: {
key1: "value1"
key2: "value2"
key3: "value3"
}
That being said, that can be converted to a Java Map
. But you want a List<MyEntry>
.For that, we can use a XmlAdapter
to convert the 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 myEntries
attribute with @XmlJavaTypeAdapter
@XmlRootElement
public class MyResponse {
...
protected List<MyEntry> myEntries;
...
@XmlJavaTypeAdapter(MyEntryAdapter.class)
public List<MyEntry> getMyEntries() {
return myEntries;
}
...
}
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 (overrode toString in MyEntry)
id: 1
Department: Hard Knocks
MyEntrys:
MyEntry{key=key1, value=value1}
MyEntry{key=key2, value=valu2}
I tested with 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 also tried it with the 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 printing out the Map as a String, and the POST coming back with 0 MyEntrys)
{
"department": "Hard Knocks",
"id": "1",
"myEntries": "{key1=value1, key2=valu2}"
}
Not sure why MOXy doesn't work in this case.
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.