[英]Json inside json not working in spring boot
I am trying to use JSON inside a JSON request.我正在尝试在 JSON 请求中使用 JSON。
for example:例如:
{
"name":"newdeeeepaajlf",
"category":"fsafaa",
"jsonData":{
"a":"value"
}
}
now when I am trying to get it in my DTO which has现在当我试图将它放入我的 DTO 时
private JSONObject jsonData;
it gets converted in a blank JSON它被转换成一个空白的 JSON
{}
I am stuck in this.我被困在这个。
We can use map to convert the data我们可以使用 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;
}
}
and use above class from controller like below并从控制器使用上面的类,如下所示
@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;
}
For request请求
{
"category":"json",
"name":"name",
"jsonObj": {
"a": "value"
}
}
it will print它会打印
json
name
{a=value}
you have a error in json if you have json something like below.如果您有类似下面的 json,那么您在 json 中有错误。
{
"name": "newdeeeepaajlf",
"category": "fsafaa",
"jsonData": {
"a": "value"
}
}
you can use this as a class你可以用它作为一个类
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;
}
}
also json within json is working with in spring boot its a very common scenario. json 中的 json 也在 Spring Boot 中使用,这是一个非常常见的场景。 use ObjectMapper to map json with class.
使用 ObjectMapper 将 json 映射到类。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.