UnKnown UnKnown - 12 days ago 10
Java Question

How to add two JSON formatted Java Strings together?

I have two JSON Format Strings

{"user1":{"Iden":4,"nID":1},"user2":{"Iden":5,"nID":1}} // String A JSON

{"user1":{"Iden":4,"nID":1},"user3":{"Iden":6,"nID":1},"user2":{"Iden":5,"nID":1}}


In the below program these above JSON are formatted by Eclipse IDE

This is my program:

import java.util.Map;

import org.codehaus.jackson.type.TypeReference;

import com.tradeking.at.util.JsonHelper;

public class Hi {
private static JsonHelper jsonHelper = JsonHelper.getInstance();

public static void main(String[] args) throws Exception {

Map<String, Tracker> totalCusts = null;

String A = "{\"user1\":{\"Iden\":4,\"nID\":1},\"user2\":{\"Iden\":5,\"nID\":1}}";
String B = "{\"user1\":{\"Iden\":4,\"nID\":1},\"user3\":{\"Iden\":6,\"nID\":1},\"user2\":{\"Iden\":5,\"nID\":1}}";

String totalString = A+B;

if (null != totalString) {
totalCusts = (Map<String, Tracker>) jsonHelper.toObject(
totalString, new TypeReference<Map<String, Tracker>>() {
});

}

System.out.println(totalCusts);

}

}


Tracker.java:

import org.json.JSONObject;

public class Tracker extends JSONObject{

}


When i ran the above , the Output is

{user1={}, user2={}}


if I use this:

String totalString = B + A ;


The O/p is:

{user1={}, user3={}, user2={}}


Please let me know how I can add two JSON Strings??

Answer

At the top-level, a JSON document is always a single object, array, or value. By just concatenating the two strings together, you're violating this principal. A simple workaround would be to join the two values together in an array:

String totalString =  "[" + A + ", " + B + "]";

And then parse as such. Or you could simply parse each JSON document one at a time, and then append or merge your results (I suspect you want to merge them, via Map.putAll).

Given that the values for your userN keys are empty, you probably have a bug in your JsonHelper class, but that's hard to say without seeing the code.