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.

  • why is `"Tomy":[` an array? – Scary Wombat Jan 23 '20 at 06:00
  • Does this answer your question? [Android- create JSON Array and JSON Object](https://stackoverflow.com/questions/17810044/android-create-json-array-and-json-object) – Jaymin Jan 23 '20 at 06:02
  • *Example what I want to get:* - you want invalid Json? – Scary Wombat Jan 23 '20 at 06:02
  • Thanks for the help and the one who put me dislike. Can't you see that I'm new here? – Vlad Shirpaev Jan 23 '20 at 06:09
  • Welcome to Stackoverflow Vlad! Please take some time to read [How to ask good questions?](https://stackoverflow.com/help/how-to-ask), as well as [this question checklist](https://codeblog.jonskeet.uk/2012/11/24/stack-overflow-question-checklist/). Also please try to create a [minimal reproducible example](https://stackoverflow.com/help/minimal-reproducible-example) of your own attempt and show it to us. – Smile Jan 23 '20 at 06:32

1 Answers1

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)); enter code here

Shubham Pandey
  • 1,788
  • 2
  • 18
  • 24