0

I have one JSON file in my app's data folder.

 {
  "user": [
    {
      "identifier": "1",
      "name": "xyz",
      "contact": [
        {
          "contact": "123"
        },
        {
          "contact": "456"
        }
      ]
    }
  ]
}

Now I want to add a new user at runtime like this.

{
  "user": [
    {
      "identifier": "1",
      "name": "xyz",
      "contact": [
        {
          "contact": "123"
        },
        {
          "contact": "456"
        }
      ]
    }
  ],
  "user": [
    {
      "identifier": "2",
      "name": "abc",
      "contact": [
        {
          "contact": "445"
        },
        {
          "contact": "789"
        }
      ]
    }
  ]
}

For that, I have this code but it simply overrides the existing user.

String lastObject = getStringFronFile(new FileInputStream(file));
        try {
            JSONObject prevJSONObj = new JSONObject(lastObject);
            prevJSONObj.put("sticker_packs",newUserArray);
            writeJsonFile(file,prevJSONObj);
        }
        catch (Exception e) {
            Log.d("Json Error", e.toString());
        }

writeJsonFile is a method for writing in the file.

Any help will be appreciated.

2 Answers 2

2

The structure you defined above is wrong, you cannot define two node with the same name user in a JSONObject.

If you want to store a list of user in to a file, you may store it like:

[
    {
        "name":"Jack",
        "age" :20
    },
    {
        "name":"Tom",
        "age" :20
    }
]

By the way, why not use SQLite database?

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

1 Comment

Thanks for giving you valuable answer. I am new to android so I ma learning and I am surely use SQLite database in future.
0

Gson simplifies this work. Add the gson dependency https://github.com/google/gson or retrofit's gson (both are same) implementation 'com.squareup.retrofit2:converter-gson:2.4.0'. From your details constructed the following pojo classes :

public class Example {
@SerializedName("user")
@Expose
private List<User> user = null;

public List<User> getUser() {
return user;
}

public void setUser(List<User> user) {
this.user = user;
}
}

public class User {
@SerializedName("identifier")
@Expose
private String identifier;
@SerializedName("name")
@Expose
private String name;
@SerializedName("contact")
@Expose
private List<Contact> contact = null;

public String getIdentifier() {
return identifier;
}

public void setIdentifier(String identifier) {
this.identifier = identifier;
}

public String getName() {
return name;
}

public void setName(String name) {
this.name = name;
}

public List<Contact> getContact() {
return contact;
}

public void setContact(List<Contact> contact) {
this.contact = contact;
}
}

public class Contact {
@SerializedName("contact")
@Expose
private String contact;

public String getContact() {
return contact;
}

public void setContact(String contact) {
this.contact = contact;
}
}

You can use the following snippet to get details from string and append your dynamic data and update the file.

String lastObject = getStringFromFile(new FileInputStream(file));
Example newJsonToReplace = new Example();
List<User> usersList = new ArrayList();
try{
    Type typeOfObject = new TypeToken<Example>() {
    }.getType(); // type you will be getting from string
    Example example = new Gson().fromJson(lastObject, typeOfObject); // converting string to pojo using gson
    if(example != null){
        usersList.addAll(example.getUser());
    }
    usersList.add(yourYourToAdd); // add your user object
    newJsonToReplace.setUser(usersList);
    String updatedList = new Gson().toJson(newJsonToReplace, typeOfObject); // again converting to json to string
    writeJsonFile(updatedList); // will replace the existing content
}catch(Exception exception){
    Log.d("Json Error", e.toString());
}

1 Comment

Thanks for your valuable answer it helps me a lot.

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.