Search code examples
javajsonjson-simple

Add a name to JsonArray or JsonObject using Java [ json-simple.jar library]


First of all i am using json-simple-2.1.2.jar[ Link on GitHub ].

It is similar to json-simple-1.1.1.jar but some classes are updated and some some other are deprecated but the logic is the same.


Java code [It produces the below]

 //JSON Array [ROOT]
    JsonArray json = new JsonArray();

    //Libraries Array
    JsonArray libraries = new JsonArray();
    for (int i = 0; i < 2; i++) {
        JsonObject object = new JsonObject();
        object.put("name", "library->" + i);
        libraries.add(object);
    }

    //Add to ROOT ARRAY
    json.add(libraries);

    //Write to File
    try (FileWriter file = new FileWriter(jsonFilePath)) {
        file.write(json.toJson());
        file.flush();
    } catch (IOException e) {
        e.printStackTrace();       
    }

Produced json file:

[
    [
        {
            "name": "library->0"
        },
        {
            "name": "library->1"
        }
    ]
]

What i want:

[   
  "libraries":[
        {
            "name": "library->0"
        },
        {
            "name": "library->1"
        }
    ]
]

As you can see JsonArray has a name for example : "libraries" .

I can't find any way to do this with neither of json-simple.jar i use.

Help is a lot appreciated :)


Solution

  • The expected JSON format expected in question is not a valid JSON. It can be verified here JSONLINT.com

    If you replace the starting and angular brackets to Flower brackets, it would be valid JSON. PFB code to build the same.

    import org.json.simple.JsonArray;
    import org.json.simple.JsonObject;
    
    import java.io.*;
    
    public class Test {
    
        public static void main(String[] args)
                throws FileNotFoundException {
    
            //JSON Array [ROOT]
            JsonObject finalOutput = new JsonObject();
    
            //Libraries Array
            JsonArray libraries = new JsonArray();
            for (int i = 0; i < 2; i++) {
                JsonObject object = new JsonObject();
                object.put("name", "library->" + i);
                libraries.add(object);
            }
    
            finalOutput.put("libraries", libraries);
    
            //Write to File
            try (FileWriter file = new FileWriter("C:\\Users\\b21677\\output.json")) {
                file.write(finalOutput.toJson());
                file.flush();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    
    }