首页 > 解决方案 > json里面的Json在spring boot中不起作用

问题描述

我正在尝试在 JSON 请求中使用 JSON。

例如:

{
"name":"newdeeeepaajlf",
"category":"fsafaa",
"jsonData":{
   "a":"value"
}
}

现在当我试图将它放入我的 DTO 中时

private JSONObject jsonData;

它被转换成一个空白的 JSON

{}

我陷入了困境。

标签: javajsonspring-boot

解决方案


我们可以使用map来转换数据

public class TestModel {
    private String name;
    private String category;
    private Map<String, Object> jsonObj;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getCategory() {
        return category;
    }

    public void setCategory(String category) {
        this.category = category;
    }

    public Map<String, Object> getJsonObj() {
        return jsonObj;
    }

    public void setJsonObj(Map<String, Object> jsonObj) {
        this.jsonObj = jsonObj;
    }

}

并从控制器中使用上面的类,如下所示

@PostMapping("/test")
    public boolean test(@RequestBody TestModel model) {

        System.out.println(model.getCategory());
        System.out.println(model.getName());
        JSONObject jsonObj = new JSONObject(model.getJsonObj());
        System.out.println(jsonObj);

        return true;
    }

请求

{
    "category":"json",
    "name":"name",
    "jsonObj": {
        "a": "value"
    }
}

它会打印

json
name
{a=value}

推荐阅读