繁体   English   中英

json中的Json在spring boot中不起作用

[英]Json inside json not working in spring boot

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

例如:

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

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

private JSONObject jsonData;

它被转换成一个空白的 JSON

{}

我被困在这个。

我们可以使用 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}

如果您有类似下面的 json,那么您在 json 中有错误。

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

你可以用它作为一个类

public class Codebeautify {
 private String name;
 private String category;
 JsonData jsonDataObject;


 // Getter Methods 

 public String getName() {
  return name;
 }

 public String getCategory() {
  return category;
 }

 public JsonData getJsonData() {
  return jsonDataObject;
 }

 // Setter Methods 

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

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

 public void setJsonData(JsonData jsonDataObject) {
  this.jsonDataObject = jsonDataObject;
 }
}
public class JsonData {
 private String a;


 // Getter Methods 

 public String getA() {
  return a;
 }

 // Setter Methods 

 public void setA(String a) {
  this.a = a;
 }
}

json 中的 json 也在 Spring Boot 中使用,这是一个非常常见的场景。 使用 ObjectMapper 将 json 映射到类。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM