I am trying to create the next json object in java dynamically, for example, if the WARN object does not exist, add it or whatever, followed by a new label message object in an additional array.
This is an example of what I'm trying to dynamically build.
{
"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"
}
]
}
This is what I tried.
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));
}
}
However, this is my result that you see is incorrect. I cannot add a title to the fact that my warnings are. Types are in only one object.
{
"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"
}
]
}
]
}
I can’t understand how to build this object dynamically, any help would be appreciated.