Tolgay Toklar Tolgay Toklar - 3 months ago 33
Java Question

Concat two json objects in java

I want to concat multiple json object.

I have two json like this

{"message":"test","status":"0"}


and this

{"message":"test-2","status":"1"}


result must be

[{"message":"test","status":"0"},{"message":"test-2","status":"1"}]


How can I do this in Java ?

Answer

Do something like this:

List<String> array = new ArrayList<String>();
array.add("{\"message\":\"test\",\"status\":\"0\"}");
array.add("{\"message\":\"test-2\",\"status\":\"1\"}");
array.toString();

If you want to user support for JSON object in Java, consider using Gson:

import com.google.gson.JsonArray;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;

public class Main {

    public static void main(String[] args) {
        JsonObject json1 = (JsonObject) new JsonParser().parse("{\"message\":\"test\",\"status\":\"0\"}");
        JsonObject json2 = (JsonObject) new JsonParser().parse("{\"message\":\"test-2\",\"status\":\"1\"}");
        JsonArray array = new JsonArray();
        array.add(json1);
        array.add(json2);
        System.out.println(array.toString());
    }
}

This would give you what you want this time using objects.