0

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 Answers2

1
[
    {

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);
Andreas
  • 154,647
  • 11
  • 152
  • 247
  • Needs a top-level obect as well, to contain the "numbers" array: `{ "numbers": [ … ] }` – user14387228 Oct 21 '20 at 23:21
  • @user14387228 OP was having trouble with the content of the array, this answer shows how. Since the JSON snippet in the question isn't even valid, anything outside the array is out of scope. – Andreas Oct 22 '20 at 04:47
0

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.

user14387228
  • 391
  • 2
  • 4