我想動態地在java中構建下面的json對象,例如,如果WARN對象不存在,添加它或任何其他的,然後添加一個新的標籤消息對象到子陣列。需要幫助建立JSONObject java
這是我試圖動態構建的一個例子。
{
"warnings" : [
{
"WARN" : [
{
"label" : "Label Goes Here",
"message" : "Message Goes Here"
},
{
"label" : "Label Goes Here2",
"message" : "Message Goes Here2"
}
],"title" : "Please review the following warnings"
},
{
"NOTIFICATION" : [
{
"label" : "Label Goes Here3",
"message" : "Message Goes Here3"
},
{
"label" : "Label Goes Here4",
"message" : "Message Goes Here4"
}
],"title" : "Please review the following warnings"
}
]
}
這是我試過的。
public class Warning {
warningTypes = new JSONObject();
}
private JSONObject warningTypes;
public Warning() {
public Warning(WarningType warningType, String label, String message) {
this.warningType = warningType;
this.label = label;
this.message = message;
}
public void add(WarningType warningType, String label, String message) {
addToJSON(warningType, new JSONObject("label",label,"message",message));
}
private void addToJSON(WarningType warningType, JSONObject jsonObj) {
if(warningTypes.has(warningType.name())) {
JSONArray array = warningTypes.getJSONArray(warningType.name());
array.put(jsonObj);
} else {
warningTypes.put(warningType.name(), new JSONArray(jsonObj));
}
}
public JSONObject toJSON() {
return new JSONObject("warnings", new JSONArray(warningTypes));
}
}
但是,這是我的結果,你可以看到是不正確的。我無法將標題do添加到我的warningTypes正在處理的事實中,但只能添加到單個對象中。
{
"warnings" : [
{
"WARN" : [
{
"label" : "Label Goes Here",
"message" : "Message Goes Here"
},
{
"label" : "Label Goes Here2",
"message" : "Message Goes Here2"
}
],
"NOTIFICATION" : [
{
"label" : "Label Goes Here3",
"message" : "Message Goes Here3"
},
{
"label" : "Label Goes Here4",
"message" : "Message Goes Here4"
}
]
}
]
}
我無法弄清楚如何動態構建這個對象,任何幫助將不勝感激。
?我喜歡你的方法。 –
你可以使用像Jackson這樣的好庫來序列化/反序列化POJO。 – Neel
我喜歡谷歌GSON。看到我的答案非常簡短的例子。 – Monir