I have a lot of attributes coming as dot-delimited strings like "company.id", "company.address.number", "user.name", "isAtive", and I need to create a nested JSON with their respective values. These attributes and values are in a HashMap.
Not everything has 3 levels of depth: many are only 1 level deep and many are deeper than 3 levels.
Code sample:
public static void main(String[] args) {
Map<String, String[]> list = new HashMap<>();
list.put("params.isAtive", new String[] {"true"});
list.put("params.user.name", new String[] {"John Diggle"});
list.put("params.company.id", new String[] {"1"});
list.put("params.company.name", new String[] {"SICAL MOTORS"});
list.put("params.company.address.number", new String[] {"525"});
list.put("params.company.address.street", new String[] {"Park Avenue"});
list.put("params.models", new String[] {"55", "65"});
JSONObject jsonReq = new JSONObject();
for(Entry<String, String[]> entry : list.entrySet()) {
String key = entry.getKey().replaceAll("params\.", "");
String value = entry.getValue().length == 1 ? entry.getValue()[0] : Arrays.toString(entry.getValue());
String [] spl = key.split("\.");
if(spl.length == 1) {
jsonReq.put(key, value);
} else {
for (int i = 0; i < spl.length; i++) {
if(i == spl.length - 1) {
jsonReq.getJSONObject(spl[i-1]).put(spl[i], value);
} else {
if((i-1) > 0) {
if(!jsonReq.getJSONObject(spl[i-1]).has(spl[i])) {
jsonReq.getJSONObject(spl[i-1]).put(spl[i], new JSONObject());
}
} else {
if(!jsonReq.has(spl[i])) {
jsonReq.put(spl[i], new JSONObject());
}
}
}
}
}
}
System.out.println(jsonReq.toString());
}
Current result:
{"models":"[55, 65]","address":{"number":"525","street":"Park Avenue"},"company":{"name":"SICAL MOTORS","id":"1"},"user":{"name":"John Diggle"},"isAtive":"true"}
Expected result:
{"models":"[55, 65]","company":{"name":"SICAL MOTORS","id":"1","address":{"number":"525","street":"Park Avenue"}},"user":{"name":"John Diggle"},"isAtive":"true"}
Remembering that it is not necessary to use JSONObject, if you opt for another one, that's fine, I just need to resolve the issue.