How do I write a string and integer into a JSON Array with Java?

1.8k Views Asked by At

I'm trying to create the following results in a JSON file:

  "numbers": [
    {
        "small": 2,
        "large": 5,
        "type": "single"
    },
    {
        "small": 10,
        "large": 50,
        "type": "double"
    }]

I can't seem to figure out how to use JSON Simple to make this happen (coding in Java). When I use:

JSONObject obj = new JSONObject();
obj.put("small", 2);

it doesn't add it to the array. When I create an array:

JSONArray nums = new JSONArray();
nums.add("small", 2)

it doesn't work because add() won't take two parameters.

Please help!

2

There are 2 best solutions below

2
On
[
    {

That means an array ([ ]) of object ({ }).

So:

JSONObject obj1 = new JSONObject();
obj1.put("small", 2);
obj1.put("large", 5);
obj1.put("type", "single");

JSONObject obj2 = new JSONObject();
obj2.put("small", 10);
obj2.put("large", 50);
obj2.put("type", "double");

JSONArray nums = new JSONArray();
nums.add(obj1);
nums.add(obj2);
0
On

You have a top level object, which contains one field named "numbers", which is an array of objects, each of which contains three fields.

So it's likely something like:

JSONobject top = new JSONobject();
JSONarray arr = new JSONarray();
top.put("numbers", arr);

then for each element in the array

JSONobject obj1 - new JSONobject();
obj1.put("small", 2);
obj1.put("large", 4);
arr.add(obj1);

etc.

I'm not familiar with that particular API but the details depend only on JSON.