T
T
TomYol2021-03-07 00:45:41
Java
TomYol, 2021-03-07 00:45:41

How to add values ​​to json array?

How can i write new data to json array? I have a json file, it has an array of Workers, which consists of the name, age, pay, post keys and their values. How can I write 4 more of the same keys to this array? I am using the Simple Json library

json
{
  "Workers": [
  {
    "name": "Имя1",
    "post": "Должнось1",
    "age": 24,
    "pay": 20000
  },
  {
    "name": "Имя2",
    "post": "Должнось2",
    "age": 25,
    "pay": 16000
  }
    //Добавить вот так
    // {
    //    "name": "Имя3"
    //    "post": "Должность3"
    //    "age": "27"
    //    "pay": "15000"
    // },
]
}

The code I'm reading the file with
FileReader reader = new FileReader(filePath);

 JSONParser jsonParser = new JSONParser();
 JSONObject jsonObject = (JSONObject) jsonParser.parse(reader);

 JSONArray lang= (JSONArray) jsonObject.get("Workers");
 Iterator i = lang.iterator();
 while (i.hasNext()) {
    JSONObject innerObj = (JSONObject) i.next();
    System.out.println("ФИО: " + innerObj.get("name") + "\n"
            + "Должность: " + innerObj.get("post") + "\n"
            + "Возраст: " + innerObj.get("age") + "\n"
            + "Зарплата: " + innerObj.get("pay") + "\n");

Answer the question

In order to leave comments, you need to log in

1 answer(s)
O
Orkhan, 2021-03-07
@TomYol

Here is the solution for Jackson:
https://stackoverflow.com/questions/43981487/how-t...
Here is the solution for Gson:
https://stackoverflow.com/questions/47111676/gson-...
Here is the solution for SImple Json:
https://stackoverflow.com/questions/50402343/how-t...

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question