Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using JSON.simple to create objects and arrays with key and value

Tags:

java

json

arrays

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


1 Answers

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);
like image 100
Shivam Avatar answered Dec 04 '25 06:12

Shivam



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!