有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java在不知道属性名和属性数的情况下处理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控制器中处理它


共 (2) 个答案

  1. # 1 楼答案

    你必须使用java获取密钥。util。迭代器

    JSONObject jsonObj = new JSONObject(JSONString);
    Iterator keys = jsonObj.keys();
    while (keys.hasNext()) {
         String keyStr = keys.next().toString();
         String value = jsonObj.getStrin(keyStr);
    }
    

    或者你可以试试这个:

    JSONObject jsonObj = new JSONObject(JSONString);
    if (jsonObj.has("key")) {
        String value = jsonObj.getString("key");
    }
    
  2. # 2 楼答案

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

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

    并在控制器中将其作为@RequestBody接受:

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

    你可以阅读更多关于JsonNode here.