3

I just picked up JSON.simple - A simple Java toolkit for JSON, which resides in https://code.google.com/p/json-simple/. I need to create Json Arrays with key => values, intead of just the value string. For Example i have this code below

import org.json.simple.JSONArray;
import org.json.simple.JSONObject;

    public class JsonSimpleExample {
         public static void main(String[] args) {

        JSONObject obj = new JSONObject();
        obj.put("name", "mkyong.com");
        obj.put("age", new Integer(100));

        JSONArray list = new JSONArray();
        list.add("msg 1");
        list.add("msg 2");
        list.add("msg 3");

        obj.put("messages", list);
       }
    }

Which produces:

{
    "age":100,
    "name":"mkyong.com",
    "messages":[
                 "msg 1",
                 "msg 2",
                 "msg 3"
               ]
}

Now I need to create a Json object and Array with key => value instead of just String as values. Like this below:

{
    "age":100,
    "name":"mkyong.com",
    "messages":[ 
                { 
                   "msg1" : "1", 
                   "msg2" : "2", 
                   "msg3" : "3" 
                }
               ]
}

Please how can i achieve this? Thanks

3 Answers 3

4

For that you required 2 more JSONObjects and also to provide a key to the object that you are putting in array. Example;

JSONObject obj = new JSONObject();
    obj.put("name", "mkyong.com");
    obj.put("age", new Integer(100));

    JSONArray list = new JSONArray();
    JSONObject obj2 = new JSONObject();
    JSONObject obj3 = new JSONObject();
    obj3.put("msg 1","1");
    obj3.put("msg 2","2");
    obj3.put("msg 3","3");
    obj2.put("obj3",obj3);
    list.put(obj2);
    obj.put("messages", list);
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks, you first code actually worked. But in a different way. I like the Edited one better though. changed your list.put to list.add. Guess that was a mistake.
No that wasn't a mistake, that's because of the different JSON jars we are using. But anyway good to help you :)
2

Simply create a new JsonObject and add it to JsonArray instead of String.

import org.json.simple.JSONArray;
import org.json.simple.JSONObject;

public class JsonSimpleExample {
     public static void main(String[] args) {

    JSONObject obj = new JSONObject();
    obj.put("name", "mkyong.com");
    obj.put("age", new Integer(100));

    JSONArray list = new JSONArray();
    JSONObject innerObj = new JSONObject();
    innerObj.put("msg1", "1");
    list.add(innerObj);


    obj.put("messages", list);
   }
}

Comments

0

So instead of Strings put into your list JSONObjects.

JSONObject listobj = new JSONObject();
listobj.put("msg1", "1");

JSONArray list = new JSONArray();
list.add(listobj);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.