1

I'm using this code:

JSONObject jO = new JSONObject();

try {
    jO.put("item1", true);
    jO.put("item2", value2);
    jO.put("item3", value3);
} catch (JSONException e1) {
    // TODO Auto-generated catch block
    e1.printStackTrace();
}

String json = null;
try {
    json = jO.toString(4);
} catch (JSONException e1) {
    // TODO Auto-generated catch block
    e1.printStackTrace();
}

File jsonFile = new File(nContext.getDir("json", 0), "dashboard.json");
//simple utility method to write the json file
Utils.writeToFile(jsonFile, json);

to have this result:

{
    "item3": "12345",
    "item2": "abcde",
    "item1": true
}

What I want to achieve, on the next run of the same piece of code, is to end with something like:

{
    "pass1": {
        "item3": "12345",
        "item2": "abcde",
        "item1": true
    },
    "pass2": {
        "item3": "67890",
        "item2": "zxcvb",
        "item1": true
    }
}

Or maybe is it better to have this?

{
    "pass1": [
        {
            "item3": "12345",
            "item2": "abcde",
            "item1": true
        }
    ],
    "pass2": [
        {
            "item3": "67890",
            "item2": "zxcvb",
            "item1": true
        }
    ]
}

I know this implies a change in the code to include a "nested" object/array. Which one is better, considering that I'll have to parse the JSON to build a ListView? Any ideas?

3
  • first time when your code execute, there will be no "pass1" like tag in json output right? But can't it be added when there is only one child in that object. Commented Jun 6, 2013 at 9:46
  • Yes, I want to add "pass1" on 1st pass also. And then continue with later passes. Commented Jun 6, 2013 at 9:49
  • so i think will be your first output something like this -> { "pass1": { "item3": "12345", "item2": "abcde", "item1": true } } Commented Jun 6, 2013 at 9:52

2 Answers 2

2

I found the solution, thanks to the comments by other users and to a "retired" answer, not present here anymore. Maybe it was my fault not being clear.

public void addEntryToJsonFile(Context ctx, String id, String name, String size) {

    // parse existing/init new JSON 
    File jsonFile = new File(ctx.getDir("my_data_dir", 0), "my_json_file.json");
    String previousJson = null;
    if (jsonFile.exists()) {
        try {
            previousJson = Utils.readFromFile(jsonFile);
        } catch (IOException e) {
            e.printStackTrace();
        }
    } else {
        previousJson = "{}";
    }

    // create new "complex" object
    JSONObject mO = null;
    JSONObject jO = new JSONObject();

    try {
        mO = new JSONObject(previousJson);
        jO.put("completed", true);
        jO.put("name", name);
        jO.put("size", size);
        mO.put(id, jO); //thanks "retired" answer
    } catch (JSONException e) {
        e.printStackTrace();
    }

    // generate string from the object
    String jsonString = null;
    try {
        jsonString = mO.toString(4);
    } catch (JSONException e) {
        e.printStackTrace();
    }

    // write back JSON file
    Utils.writeToFile(jsonFile, jsonString);

}
Sign up to request clarification or add additional context in comments.

3 Comments

can you please explain what the line: mO.put(String.valueOf(id), jO); means? What is the id variable and what is this line doing?
Hi. Answer edited. [the two methods from Utils read and write a file from a string.]
Anyway, the line mO.put(id, jO) adds the "nested" object jO to the base object mO. You can see a reference for this scheme into the question above.
1

Edited after dentex comment

  1. Read your file
  2. Parse the root Json object
  3. If the root object not is already a complex object
    1. Create a new root object
    2. put your root object in it
  4. put your second object in the root object
  5. Write bnack your file

in pseudo code:

oldJson = ParseJsonFromFile()
newJson = {"item1": true, "item2": "abcde" ...}
JSONObject root;
if (oldJson.hasKey("pass1") {
    root = oldJson
} else {
    root = new JSONObject()
    root.add("pass1", oldJson)
}
root.add("pass" + root.getSize() + 2, newJson)
WriteJsonToFile(root)

3 Comments

Yes, this is what I meant. The only difference is that on every pass I have to append ONE new object to an existing json file. Ending with two objects, before, was just an example. ;)
the difficulty, then, is that on your first pass you have a simple object, and after the second pass, you have a complex object.
thanks @njzk2 for your efforts. Maybe I was not clear enough. My sequence should be 1. parse json file (1st time ever it will be empty); 2. put one "complex" object from every pass; 3. write back the Json file every time. ;)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.