簡體   English   中英

在不知道屬性名稱和屬性數量的情況下處理json對象

[英]Handles json objects without knowing the attribute name and number of attributes

我嘗試使用以下示例處理請求:

"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控制器中處理它?

您可以在資源類中使用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的信息。

您必須使用java.util.Iterator獲取密鑰。

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");
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM