1

So I have a situation where I am fetching some data from a database which I can't change/update. So my data from 2 columns coming like this:

For example:

        Column1             Column2
Row 1: hello.how.are.you    Gracie
Row 2: hello.how.is.she     John
Row 3: hello.how.is.he      Gurinder   
Row 4: hello.from.me        Singh

So I need to create a JSON which will look like:

{  
   "hello":{  
      "how":{  
         "are":{  
            "you":"Gracie"
         },
         "is":{  
            "he":"Gurinder",
            "she":"John"
         }
      },
      "from":{  
         "me":"Singh"
      }
   }
}

I want some optimize way to create my JSON. Thanks!

public static void main(String[] args) {

    List<String > stringList = new ArrayList();
    stringList.add("hello.how.are.you");
    stringList.add("hello.how.is.she");
    stringList.add("hello.how.is.he");
    stringList.add("hello.from.me");

    JSONObject response = new JSONObject();

    for (String str : stringList) {

            String[] keys = str.split("\\.");

            for (int i = 0; i < keys.length; i++) {

                if (response.has(keys[i])) {

                } else {
                    JSONObject jsonObject2 = new JSONObject()
                    response.append(keys[i], jsonObject2);

                }
            }
        }
    }

I am doing something like this and trying to solve.

Gurinder
  • 943
  • 2
  • 9
  • 19

2 Answers2

0

What you're using for input needs to hold all of the data (Including Column 2). Let's say the input variable is a HashMap<String, String> equal to

{
    "hello.how.are.you" : "Gracie",
    ...
}

At the moment, your code looks like its on track. The issue is, you're appending to response, when you want to append to some value deep in the JSON tree.

JSONObject parent = response;
for(...) {
    // If there's no JSON there, just make it
    if( !parent.has(keys[i]) ) {
        // It's not already in there, so let's make it
        parent.put(keys[i], new JSONObject()); // response["hello"] = {}
    }
    // Now, look at how this works. If keys = ["hello", "how", "are", "you"],
    // Then when i == 0, parent <= response["hello"]
    // That way you do response["hello"].append("how", {}) on the next iteration
    parent = (JSONObject)parent.get(keys[i]);
}

You'll also need to handle the tail case, which you can do with something like

if( i == keys.length - 1 ) {
    parent.put(keys[i], input.get(str)); // str = "hello.how.are.you"
    // input.get("hello.how.are.you") == "Gracie"
} else ...
Nicholas Pipitone
  • 4,002
  • 4
  • 24
  • 39
  • Thanks for quick reply! But this code wouldn't work, this above code will create "hello", "are", "how", "you" as a separate structure {"how":[{}],"are":[{}],"hello":[{}],"you":[{}]} like this. I want hello.how.are.you should be { "hello":{ "how":{ "are":{ "you":"Gracie" }, "is":{ "he":"Gurinder", "she":"John" } }, "from":{ "me":"Singh" } } } They should be present internally not parallelly. – Gurinder Aug 03 '18 at 17:15
  • if (!target.has(key)) { target.put(key, new JSONObject()); } target = target.getJSONObject(key); This approach is working. I tried this one. But if i use your code => parent.append(keys[i], new JSONObject()); Its creating new json object on parallel level – Gurinder Aug 03 '18 at 17:26
  • Ah, that's a library-specific quirk. I'll update my code, I haven't used the JSONObject library so I just imitated the function call you used. – Nicholas Pipitone Aug 03 '18 at 17:28
  • Does `.get` still work, or does that have to be `.getJSONObject`? I imagine `.get` works. Regardless, it's just a lil update from `append` to `put`. The former must've implicitly instantiated a JSONArray as opposed to throwing an error. – Nicholas Pipitone Aug 03 '18 at 17:29
0

So I solved this by using this approach :

    public static void main(String... r) {

    String[] keys = myString.split("//.");

    JSONObject target = new JSONObject();

    int lastValueIndex = keys.length - 1;

    for (int i = 0; i < keys.length; i++) {

        String key = keys[i];

        if (!target.has(key) && (lastValueIndex == i)) {

            target.put(key, myValue);

            break;

        } else if (!target.has(key)) {
            target.put(key, new JSONObject());
        }

        target = target.getJSONObject(key);

    }

}

Try your own way before using my code, Thanks!

Gurinder
  • 943
  • 2
  • 9
  • 19