Home > Back-end >  How to add a new field to my json object programatically?
How to add a new field to my json object programatically?

Time:09-29

i am having a json data in file . I would like to add a new field to each object in my json array. for example if my file is

[
  {
    "inventory": "SMS",
    "flight_name": "Very Very long long flight"
  },
  {
    "inventory": "SMS",
    "flight_name": "Very Very long long flight"
  },
  {
    "inventory": "MMS",
    "flight_name": "Short Flight"
  }
]

I would like to add a new field created_by. the follow is how i want to transform my json data.

[
  {
    "inventory": "SMS",
    "flight_name": "Very Very long long flight",
    "created_by": "Felix"
  },
  {
    "inventory": "SMS",
    "flight_name": "Very Very long long flight",
    "created_by": "Felix"
  },
  {
    "inventory": "MMS",
    "flight_name": "Short Flight",
    "created_by": "Felix"
  }
]

In reality my file is large, so i cannot manually add . How can i programatically add the new field .or if any online tool is available please let me know

thank you so much

CodePudding user response:

package test.riot.json.json;

import java.io.File;
import java.io.FileReader;
import java.util.List;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonElement;

/**
 * Hello world!
 *
 */
public class App {
    public static void main(String[] args) {

        GsonBuilder builder = new GsonBuilder();
        Gson gson = builder.create();

        File file = new File("/Users/kannan/openmindcvs/json/src/main/java/test/riot/json/json/json.txt");

        try (FileReader fileReader = new FileReader(file)) {

            char[] chars = new char[(int) file.length()];

            fileReader.read(chars);

            String fileContent = new String(chars);

            JsonElement element = gson.toJsonTree(fileContent);

            List<com.google.gson.internal.LinkedTreeMap> jsonObjectsArr = gson.fromJson(element.getAsString(),
                    List.class);

            jsonObjectsArr.forEach(e -> {
                e.putIfAbsent("created_by", "0c9d6015-f45f-4a90-a58c-8c99384aa40");
                e.putIfAbsent("first_name", "Campaign");
                e.putIfAbsent("last_name", "Manager");

            }

            );

            System.out.println(gson.toJson(jsonObjectsArr));

        } catch (Exception e) {
            System.err.println(e);
        }

    }
}

CodePudding user response:

In a similar case, I would personnaly open the file with Sublime text regex

Assuming you only have one file to update, that's for me the fastest and easiest solution !

  •  Tags:  
  • json
  • Related