Search code examples
javajsonjson-simple

How do I create a JSONObject?


I'm trying to "create" a JSONObject. Right now I'm using JSON-Simple and I'm trying to do something along the lines of this (sorry if any typo's are made in this example JSON file)

{
    "valuedata": {
        "period": 1,
        "icon": "pretty"
    }
}

Right now I'm having issues finding on how to write valuedata into a JSON file through Java, what I did try was:

Map<String, String> t = new HashMap<String, String>();
t.put("Testing", "testing");
JSONObject jsonObject = new JSONObject(t);

but that just did

{
    "Testing": "testing"
}

Solution

  • Whatr you want to do is put another JSONObject inside your JSONObject "jsonObject", in the field "valuedata" to be more exact. You can do this like that...

    // Create empty JSONObect here: "{}"
    JSONObject jsonObject = new JSONObject();
    
    // Create another empty JSONObect here: "{}"
    JSONObject myValueData = new JSONObject();
    
    // Now put the 2nd JSONObject into the field "valuedata" of the first:
    // { "valuedata" : {} }
    jsonObject.put("valuedata", myValueData);
    
    // And now add all your fields for your 2nd JSONObject, for example period:
    // { "valuedata" : { "period" : 1} }
    myValueData.put("period", 1);
    // etc.