David Findlay David Findlay - 3 months ago 14
Java Question

Converting inbound JSON message to Java Object with Spring

I'm trying to create a Java object by deserialising a JSON message in Spring Boot. I have a class as such:

public class Status implements Serializable {
private int uptime;
}


Then I have a Rest Controller as such:

@RestController
public class StatusReceiver {

@RequestMapping(value = "/poststatus", method = RequestMethod.POST)
public @ResponseBody Status storeStatus(@RequestBody Status statusMessage) {

System.out.println("Uptime: " + statusMessage.getUptime());

return statusMessage;

}

}


I definitely don't understand a fair bit of what I'm doing here. I want the controller to be creating a Status object when it receives the message and have it store it in the database.

Output of this code is:

Uptime: 0


The message it's receiving is:

{
"Status": [
{
"uptime": 12345.0
}
]
}


I'm obviously missing something. How can I have Spring convert the JSON object into the Status java object? Also where is the return from the method meant to be going and doing?

Answer

The request body JSON is not matching the Status object structure. Either your body should be

{uptime: 12345.0}

or the Status class should be

class Status {
   List<Map<String, Long>> status = new ArrayList<>();
}

Instead of having a List of Map, you can define a new class and have a list of this new class

class StatusInfo{
   long uptime;
}

class Status {
   List<StatusInfo> status = new ArrayList<>();
}