首页 > 解决方案 > 在不知道属性名称和属性数量的情况下处理 json 对象

问题描述

我尝试使用以下示例处理请求:

"type" : "NEWS",
"content" : {
    "title" : "Test Message",
    "message" : "This is a message",
    "buttonCaption" : "Click me"
}

或者可能:

"type" : "NEWS",
"content" : {
    "title" : "Test Message",
    "message" : "This is a message",
    "buttonCaption" : "Click me",
    "anotherField" : "values"
}

有时可能:

"type" : "NEWS",
"content" : {
    "name" : "Test Message",
    "anotherProperties" : "This is a message",
    "ohMyGodAnotherFields" : "Click me"
}

所以我不能创建一个特定的对象。如何在 Spring 控制器中处理它?

标签: javajsonspring-boot

解决方案


您可以JsonNode在资源类中使用,例如:

public class Foo {
    private String type;
    private JsonNode content;
    // ...
}

@RequestBody在您的控制器中接受它:

@PostMapping
public ResponseEntity<Foo> foo(@RequestBody Foo foo){
   // do something with your foo...
}

您可以在此处阅读更多 aboot JsonNode


推荐阅读