0

I need a help.

I have JSON with data:

{
   "Tomy":[
   {
      "name":"Tomy",
      "age":25
   }]
}

In my app, I need to add new persons and save to JSON.

How do I need to insert a new person to the last position in JSON?

Example what I want to get::

{
   "Tomy":[
   {
      "name":"Tomy",
      "age":25
   }],
   "Boby":[
   {
      "name":"Boby",
      "age:38
   }]
}

Please help explain how to work with JSON. Or indicate the direction.

5
  • why is "Tomy":[ an array? Commented Jan 23, 2020 at 6:00
  • Does this answer your question? Android- create JSON Array and JSON Object Commented Jan 23, 2020 at 6:02
  • Example what I want to get: - you want invalid Json? Commented Jan 23, 2020 at 6:02
  • Thanks for the help and the one who put me dislike. Can't you see that I'm new here? Commented Jan 23, 2020 at 6:09
  • Welcome to Stackoverflow Vlad! Please take some time to read How to ask good questions?, as well as this question checklist. Also please try to create a minimal reproducible example of your own attempt and show it to us. Commented Jan 23, 2020 at 6:32

1 Answer 1

1

You can make a person which will be array of individual person objects, something like this below.

{
   "persons":[
   {
      "name":"Tomy",
      "age":25
   },
   {
      "name":"Boby",
      "age:38
   }]
}

public class MyJson{ private List<Person> persons; //its getter setter} and then Person class public class Person{ private String name; private int age; //its getter setter}

then code to add it into json like below

List<Persons> personLs = Lists.newArrayList(); 

personLs.add();

and then JsonUtils.getMapper().writeValueAsString(new MyJson(personLs));

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

2 Comments

Thanks. Structure of data I unintended. But I can't to insert new person to json. I need to get size of jsonArray of Person, and after to insert only?
Ok, so you will create a Person class, like below

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.