Chandz Chandz - 3 months ago 9
JSON Question

How can I receive multiple parameter values and return data in JSON format in Spring REST?

I am new to Spring and I am using Spring MVC4. I must receive all the requests, read multiple parameters in requests and finally apply business logic based on parameters and return the data in JSON format.

TestController.java:

@RequestMapping(value="/receiveUpdatedStressScore",params = { "value", "device_model"},method=RequestMethod.GET, produces={"application/json"})
public String receiveUpdatedStressScore(@RequestParam(value="value") int value,@RequestParam(value="device_model") String device_model)
{
return "Here: "+value+" device_model "+device_model;
}


URL: http://localhost:8080/appname/receiveUpdatedStressScore?value=100&device_model=nokia

But I'm getting Output which is not in Json. My output in browser is..

Here: 100 device_model nokia

How to convert it into Json?

Answer

You are returning a String which will not auto-convert to JSON. Do something like this (note the @ResponseBody and make sure you have Jackson as dependency):

 @RequestMapping(value="/receiveUpdatedStressScore")
public @ResponseBody Device receiveUpdatedStressScore(@RequestParam(value="value") int value,@RequestParam(value="device_model") String deviceModel)

{ 
    Device device = new Device();
    device.setDeviceModel(deviceModel);
    device.setValue(value);
    return device; 
}

public class Device {
    int value;
    String deviceModel;
    public int getValue() {
        return value;
    }
    public void setValue(int value) {
        this.value = value;
    }
    public String getDeviceModel() {
        return deviceModel;
    }
    public void setDeviceModel(String deviceModel) {
        this.deviceModel = deviceModel;
    }

}