0

I have a string that looks like a JSON array with objects:

myJsonArray = "[
                {\"name\":\"alex\",\"weight\":\"88\"},
                {\"name\":\"Emma\",\"weight\":\"71\"}
               ]";

What is the easiest way to add a new object to the string?

The string (myJsonArray) is saved to a file between the program session so I have to work on the string (myJsonArray).

I know that Gson have a nice way to convert the string array into Java objects:

 MyClass[] person = gson.fromJson(myJsonArray,MyClass[].class);

Maybe Gson have a nice way? or not...

2 Answers 2

2

The easiest way is to create a POJO model of every Json-object in your myJsonArray and then handle it in a List, Array or what ever you need ...

EXAMPLE:

public class Person{

    @SerializedName("name")

    private String name;
    @SerializedName("weight")

    private int weight;

    /**
     * @return the name
     */
    public String getName() {
        return name;
    }

    /**
     * @param name
     *            the name to set
     */
    public void setName(String name) {
        this.name = name;
    }

    /**
     * @return the weight
     */
    public int getWeight() {
        return weight;
    }

    /**
     * @param weight
     *            the weight to set
     */
    public void setWeight(int weight) {
        this.weight = weight;
    }

    @Override
    public String toString() {
        return "Person [name=" + name + ", weight=" + weight + "]";
    }

    /**
     * @return json
     */
    public String toJson() {
        return new Gson().toJson(this);
    }

}

DESERIALIZE

Gson gson = new Gson();
List<Person> personList = gson.fromJson(myJsonArray,Person.class);
personList.add(new Person());
Sign up to request clarification or add additional context in comments.

Comments

1

There is already an answer showing you how to use GSON to convert from JSON to POJO and vice versa. While that is the preferred approach from my point of view but, you can also make use of GSON only to add elements to json array.

Assuming that you have your json array string as follow:

String myJsonArray = "["  
            + "{\"name\":\"alex\",\"weight\":\"88\"},"  
            + "{\"name\":\"Emma\",\"weight\":\"71\"}"
            + "]";

Initialize Gson object as shown below:

Gson gson = new GsonBuilder().setPrettyPrinting().serializeNulls().create();

Convert your json String array to JsonElement as shown below:

JsonElement elements = gson.fromJson(myJsonArray, JsonElement.class); 

Once you have JsonElement it contains your json array then you can convert it to JsonArray as shown below:

JsonArray arr = elements.getAsJsonArray(); 

Now you have your array as JsonArray and you can print them out by iterating through the elements as shown below:

for(JsonElement e: arr) {
    System.out.println(e);
}

And that would give you (based on above string):

{"name":"alex","weight":"88"}
{"name":"Emma","weight":"71"}

Let's assume that you want to add a new object to the existing array but, you have the object in the form of json string as follow:

String newObject = "{\"name\":\"Raf\", \"weight\":\"173\"}"; 

//Creates new JsonElement from json string
JsonElement newElement = gson.fromJson(newObject, JsonElement.class);

Now you can add this element to your existing array as follow:

arr.add(newElement);

Finally you can print your new json array as we did it before:

for(JsonElement e: arr) {
    System.out.println(e);
}

And the output you get is

{"name":"alex","weight":"88"}
{"name":"Emma","weight":"71"}
{"name":"Raf","weight":"173"}

2 Comments

This works good but is it the easiest way to add a new object to the string?
It is for you to decide which approach is the easiest depending on your requirements/scope/etc of whatever you are working on. This answer uses only Gson

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.