![](/img/trans.png)
[英]Parse JSON without knowing format (can be one of two different objects)
[英]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控制器中處理它?
您必須使用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.