Reputation: 350
I have a problem with a JSON request to my REST Api.
My request is something like:
{"task":"get_objects","data":{"guid":"1234"}}
But when I want to read the "data" object in my controller it's empty.
I get an error: org.json.JSONException: JSONObject["guid"] not found.
ApiController.java:
import java.util.List;
import org.json.JSONArray;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
@RestController
@RequestMapping("/api")
public class ApiController {
@Autowired
private AssemblyRepository assemblyRepo;
@RequestMapping(method=RequestMethod.POST)
public ResponseEntity<JSONObject> sendResponse(@RequestBody AppRequest request) {
String task = request.getTask();
JSONObject data = request.getData();
String guid = data.getString("guid");
String password = data.getString("pwd");
//Do some stuff with the data
}
}
AppRequest.java:
import org.json.JSONObject;
public class AppRequest {
private String task;
private JSONObject data;
public String getTask() {
return task;
}
public void setTask(String task) {
this.task = task;
}
public JSONObject getData() {
System.out.println("AppRequest getData: " + data);
return data;
}
public void setData(JSONObject data) {
System.out.println("AppRequest getData: " + data);
this.data = data;
}
}
I also tried to change the "data" from JSONObject
to String
but then I get the message Could not read JSON: Can not deserialize instance of java.lang.String out of START_OBJECT token
I really don't see what I'm doing wrong here ^^
Upvotes: 0
Views: 3177
Reputation: 12977
Is there a reason why you are trying to work with JSONObject
and not a POJO
class? if not try something like:
class Data {
String guid;
}
public class AppRequest {
Data data;
}
and then
request.getData().getGuid();
then you don't have to work with Serializers
Upvotes: 1