Java: Convert point-delimited strings to nested JSON

Asked

Viewed 40 times

3

I have a lot of attributes coming as point-delimited strings like "company.id", "company.address.number", "user.name", "isAtive", and I need to create a nested JSON with its respective values. These attributes and values are in a Hashmap.

Not everything has 3 levels of depth: many have only 1 level of depth and many are deeper than 3 levels.

Code example:

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 choosing another has no problem, just need to resolve the issue.

1 answer

2


Hello, see if this solves for you

import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;
import org.json.JSONObject;

public class Main {

  private static void addEntry(JSONObject jsonReq, String currentkey, String value) {
    String[] keys = currentkey.split("\\.");
    JSONObject newJson = new JSONObject();
    newJson = jsonReq;
    for(int i = 0; i < keys.length-1; i++){
        if (newJson.has(keys[i])) {
            newJson = newJson.getJSONObject(keys[i]);
        }else{
            newJson.put(keys[i], new JSONObject());
            newJson = newJson.getJSONObject(keys[i]);
        }
    }
    newJson.put(keys[keys.length-1], value);
    jsonReq=newJson;
  }

  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());
        addEntry(jsonReq,key, value);
    }
    System.out.println(jsonReq.toString());
 }
}

Current result

{"models":"[55, 65]","company":{"address":{"number":"525","street":"Park Avenue"},"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"}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.