Spring 引导 Rest API 嵌套的 JSON 对象为空

Spring boot RestAPI nested JSONObject is empty

我对 REST Api 的 JSON 请求有问题。

我的要求是这样的:

{"task":"get_objects","data":{"guid":"1234"}}

但是当我想读取控制器中的 "data" 对象时,它是空的。 我得到一个错误: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;
    }
}

我也尝试将 "data" 从 JSONObject 更改为 String 但后来我收到消息 Could not read JSON: Can not deserialize instance of java.lang.String out of START_OBJECT token 我真的看不出我做错了什么^^

您尝试使用 JSONObject 而不是 POJO class 是有原因的吗?如果没有尝试类似的东西:

class Data {
  String guid;

}

public class AppRequest {
   Data data;
}

然后

request.getData().getGuid();

那么您就不必使用 Serializers