In Java, how can I combine two JSON arrays of objects? - java

I have several string each containing a JSON representation of an array of objects. Here's an example in code to illustrate, though this is not my actual code (the JSON strings are passed in):
String s1 = "[{name: "Bob", car: "Ford"},{name: "Mary", car: "Fiat"}]";
String s2 = "[{name: "Mack", car: "VW"},{name: "Steve", car: "Mercedes Benz"}]";
I need to combine those two JSON arrays into one large JSON array. I could treat this as a String manipulation problem and replace the inner end square brackets with commas but that's not particularly robust (though I am guaranteed to get valid JSON).
I'd rather treat these two Strings as JSON arrays and just add them together somehow. It's a great plan except I don't know the "somehow" part.
Does anyone know a solution in Java that doesn't require constructing Java Object representations of the JSON objects?
Thanks!

This code will take sourceArray (s2), and append it to the end of destinationArray (s1):
String s1 = "[{name: \"Bob\", car: \"Ford\"},{name: \"Mary\", car: \"Fiat\"}]";
String s2 = "[{name: \"Mack\", car: \"VW\"},{name: \"Steve\", car: \"Mercedes Benz\"}]";
JSONArray sourceArray = new JSONArray(s2);
JSONArray destinationArray = new JSONArray(s1);
for (int i = 0; i < sourceArray.length(); i++) {
destinationArray.put(sourceArray.getJSONObject(i));
}
String s3 = destinationArray.toString();

You really have only two choices: parse the JSON (which invariably would involve constructing the objects) or don't parse the JSON. Not parsing is going to be cheaper, of course.
At first glance your idea about treating it as a String-manipulation problem might sound fragile, but the more I think about it, the more it seems to make fine sense. For error detection you could easily confirm that you were really dealing with arrays by checking for the square brackets; after that, just stripping off the ending bracket, adding a comma, stripping off the beginning bracket, and adding the "tail" should work flawlessly. The only exception I can think of is if either array is empty, you should just return the other String unchanged; again, that's very easy to check for as a String.
I really don't think there's any reason to make it more complex than that.

I used this code for Combine two Json Array.
String s1 = "[{name: \"Bob\", car: \"Ford\"},{name: \"Mary\", car: \"Fiat\"}]";
String s2 = "[{name: \"Mack\", car: \"VW\"},{name: \"Steve\", car: \"Mercedes Benz\"}]";
String s3=new String("");
s1=s1.substring(s1.indexOf("[")+1, s1.lastIndexOf("]"));
s2=s2.substring(s2.indexOf("[")+1, s2.lastIndexOf("]"));
s3="["+s1+","+s2+"]";
System.out.println(s3);

And here is my solution, You may want to merge more than two arrays :
Java version:
public static JSONArray mergeMultiJsonArray(JSONArray... arrays) {
JSONArray outArray = new JSONArray();
for (JSONArray array : arrays)
for (int i = 0; i < array.length(); i++)
outArray.put(array.optJSONObject(i));
return outArray;
}
Kotlin version:
fun mergeMultiJsonArray(vararg arrays: JSONArray): JSONArray {
val outArr = JSONArray()
for (array in arrays)
for (i in 0 until array.length())
outArray.put(array.optJSONObject(i))
return outArr
}

i use this code to append all the elements of a jsonArray to a common JsonArray.
public JSONArray getMergeJsonArrays(ArrayList<JSONArray> jsonArrays) throws JSONException
{
JSONArray MergedJsonArrays= new JSONArray();
for(JSONArray tmpArray:jsonArrays)
{
for(int i=0;i<tmpArray.length();i++)
{
MergedJsonArrays.put(tmpArray.get(i));
}
}
return MergedJsonArrays;
}

This function does the magic, adding multiples arrays returning one JSONArray with all elements
public static JSONArray JoinArrays(JSONArray... jsonArrays) {
JSONArray resultJSONArray = new JSONArray();
Arrays.stream(jsonArrays).forEach(jsonArray -> IntStream.range(0, jsonArray.length()).mapToObj(jsonArray::get).forEach(resultJSONArray::put));
return resultJSONArray;
}

Use Below Method pass all JSON array in ArrayList this method will return cumulative JsonArray
public JSONArray getMergeJson(ArrayList<JSONArray> xyz){
JSONArray result=null;
JSONObject obj= new JSONObject();
obj.put("key",result);
for(JSONArray tmp:patches){
for(int i=0;i<tmp.length();i++){
obj.append("key", tmp.getJSONObject(i)); ;
}
}
return obj.getJSONArray("key");
}

Related

How to get a value which is a List from a JSONObject in Java

I have a following JSON:
{"data":["str1", "str2", "str3"]}
I want to get a List, i.e. ["str1", "str2", "str3"]
My code is:
JSONObject json = new JSONObject();
List list = new ArrayList();
...
// adding data in json
...
list = (List) json.get("data");
This is not working.
you can get this data as a JsonArray
You can customize a little bit of code like it
public static void main(String[] args) throws ParseException {
String data = "{\"data\":[\"str1\", \"str2\", \"str3\"]}";
JSONObject json = new JSONObject(
data);
JSONArray jasonArray = json.getJSONArray("data");
List list = new ArrayList();
int size = jasonArray.length();
int i = 0;
while (i < size) {
list.add(jasonArray.get(i));
i++;
}
System.out.println(list);
}
You wish to parse a JSON string using Java code. It is recommended to use a JSON library for Java. There are several. The below code uses Gson. There are many online examples such as Convert String to JsonObject with Gson. You should also familiarize yourself with the Gson API.
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import java.util.ArrayList;
import java.util.List;
public class JsonList {
public static void main(String[] args) {
String json = "{\"data\":[\"str1\", \"str2\", \"str3\"]}";
JsonElement elem = JsonParser.parseString(json);
if (elem.isJsonObject()) {
JsonObject obj = elem.getAsJsonObject();
elem = obj.get("data");
if (elem.isJsonArray()) {
JsonArray arr = elem.getAsJsonArray();
List<String> list = new ArrayList<>();
int count = arr.size();
for (int i = 0; i < count; i++) {
elem = arr.get(i);
if (elem.isJsonPrimitive()) {
String str = elem.getAsString();
list.add(str);
}
}
System.out.println(list);
}
}
}
}
Running the above code gives the following output:
[str1, str2, str3]
There are other ways to convert the JsonArray to a List. The above is not the only way. As I wrote earlier, peruse the API documentation and search the Internet.
Behind the scenes, the JSONArray object stores the json data in an ArrayList<Object>, and it has a method called toList(). There's absolutely no need to loop through the JSONArray in order to set values in the array. The simpler code would look something like this
String data = "{\"data\":[\"str1\", \"str2\", \"str3\"]}";
JSONObject json = new JSONObject(data);
List<Object> list = json.getJSONArray("data").toList();
System.out.println(myList);
Note: This will create a list of generic Objects. The currently accepted answer doesn't define a type for the List, which is unsafe. It doesn't enforce type safety, and errors will occur at runtime instead of at compile time.
If you want to convert all of the inner objects to a String, you can do this by upcasting the List to an Object, and then casting it to a List<String>. I don't particularly recommend it, but it can be done like this. List<String> list = (List<String>) (Object) json.getJSONArray("data").toList();.
A better way of casting the value to a specific type would be via a stream to call the Object.toString() method.
List<String> list = json.getJSONArray("data").toList().stream().map(Object::toString).collect(Collectors.toList());
or, if you have a specific type you want to cast it to, you can use
List<MyObject> list = json.getJSONArray("data").toList().stream().map(jsonObject -> (MyObject) jsonObject).collect(Collectors.toList());
Finally, as others have pointed out, there are better libraries for dealing with json. Gson is a great library, however I personally prefer Jackson. They both offer similar resources, but I've found that Jackson's ObjectMapper is more customizable and more widely used.

how to create multiple JSON Object dynamically?

I am trying to insert data into multiple JSON objects but I don't know how to create them dynamically in android.
In the hard coded way it is something like:-
JSONArray pdoInformation = new JSONArray();
JSONObject pDetail1 = new JSONObject();
JSONObject pDetail2 = new JSONObject();
JSONObject pDetail3 = new JSONObject();
pDetail1.put("productid", 1);
pDetail1.put("qty", 3);
pDetail1.put("listprice", 9500);
pDetail2.put("productid", 2);
pDetail2.put("qty", 4);
pDetail2.put("listprice", 8500);
pDetail3.put("productid", 3);
pDetail3.put("qty", 2);
pDetail3.put("listprice", 1500);
pdoInformation.put(pDetail1);
pdoInformation.put(pDetail2);
pdoInformation.put(pDetail3);
But I want to create these JSONObject dynamically as I don't know how many of them are going to be needed while coding and in those dynamically created JSONObject the data will be filled from three ArrayList of productid, qty and listprice.
So its obvious that the number of those dynamically created JSONObject will depend on the size of any one ArrayList.
ArrayList :-
ArrayList<String> productid = new ArrayList<String>();
ArrayList<String> qty = new ArrayList<String>();
ArrayList<String> listprice= new ArrayList<String>();
List<JSONObject> myJSONObjects = new ArrayList<JSONObject> (productid.size());
for(int i=0; i<productid.size(); i++) {
JSONObject obj = new JSONObject();
obj.put("productid", productid.get(i) );
obj.put("qty", qty.get(i));
obj.put("listprice", listprice.get(i));
myJSONObjects.add(obj);
}
at the end all JSONObjects are in myJSONObjects.
I want to create these JSONObject dynamically as I don't know how many
of them are going to be needed while coding.
As you are already having ArrayList, iterate through it and create a new JSONObject in each iteration and put it inside ArrayList<JSONObject>.
For example:
JSONObject objJSON;
for(int i=0; i<numberOfItems; i++) {
objJSON = new JSONObject();
objJSON.put("productid", 1);
objJSON.put("qty", 3);
objJSON.put("listprice", 9500);
pdoInformation.put(objJSON);
}
The data will be filled from three ArrayList of productid, qty and
listprice
You shouldn't take different ArrayLists because you have to manage each lists as many as you have, instead of that create a single ArrayList of type user defined class. For example, ArrayList<Product> where Product type would contain setter/getter methods.
In this design, how will you relate data with each other if it is divided in multiple Arraylists.
It seems you need to redesign your data structure a bit.
Instead of using three ArrayLists you should keep one Arraylist.
That Arraylist will hold object of beans.
For ex.
class product{
private double productid;
private double listprice;
private long qty;
// getters and setters
}
and keep all objects in one Arraylist and then by looping through it you get all three values together while creating JSON.
JSON is just a text String. You could simply write something like:
String jsonString = "[";
jsonString = jsonString + "{\""productid\":1",\"qty\":3,\"listprice\":9500}";
jsonString = jsonString + "{\""productid\":2",\"qty\":4,\"listprice\":8500}";
jsonString = jsonString + "{\""productid\":3",\"qty\":2,\"listprice\":1500}";
...
jsonString = jsonString + "]";
This could be the raw way of doing it.
I am using (not in android but in jsp, so could not be posible) gson and it also works with arraylist object, so you can create the array of objects and after that just ask him to generate the json text.

Cast JSONObject to JSONArray. Problems with UTF8 characters

I'm trying to cast a JSONObject to JSONArray. The JSONObject contains an object of type JSONArray. The array is a sequence of strings. One of the strings in the sequence is formatted as the following.
"uid=\u00d1\u0088\u00d1\u0084\u00d1\u0088"
after doing a cast of the JSONObject to an array the characters in the array change.
"uid=???" T
After the cast to JSONArray the original double byte characters in the above \u format change to the incorrect display characters in my java program. Any ideas? Has anyone seen this problem? I have done some searching but have not come up with answers to my problem.
The code below is what't used to do this.
public static String[] read(JSONObject input)
{
com.ibm.TEPS.JSON.Any.assertTypeCode(input, _type);
JSONArray val = (JSONArray)input.get(FW_Properties.TEPSREST_TYPE_EXT_VAL);
String [] result = new String[val.size()];
for(int i = 0;i<result.length;i++)
{
result[i] = (String)val.get(i);
}
return result;
}

How to Iterate the array of json objects(gson)

I'm making a ship defense game.
I have a problem with getting the array of waypoints.
The map contains the JSON format(Using GSON)
{
"waypoints" : {
"ship": {
"first_type": [[0,0],[5,7],[2,8],[4,4],[10,10],[12,0],[0,12],[12,8],[8,8]]
},
"boat": {
"first_type": [[0,0],[5,7],[2,8],[4,4],[10,10],[12,0],[0,12],[12,8],[8,8]]
}
}
}
My code:
jse = new JsonParser().parse(in);
in.close();
map_json = jse.getAsJsonObject();
JsonObject wayPoints = map_json.getAsJsonObject("waypoints").getAsJsonObject("ship");
I wrote this one,but it doesn't work.
JsonArray asJsonArray = wayPoints.getAsJsonObject().getAsJsonArray();
How can I foreach the array of objects?
You can simplify your code and retrieve the first_type array using the following code. Same code should pretty much work for the second_type array as well:
JsonArray types = map_json
.getAsJsonObject("waypoints")
.getAsJsonObject("ship")
.getAsJsonArray("first_type";
for(final JsonElement type : types) {
final JsonArray coords = type.getAsJsonArray():
}
wayPoints is a JSON object. It contains another JSON object called ship. And ship contains a JSON array called first_type. So you should get the first_type array from the ship object, and iterate on this array.

JSON Array iteration in Android/Java

I am building an android app that needs to download and synchronise with an online database, I am sending my query from the app to a php page which returns the relevant rows from a database in JSON format.
can someone please tell me the best way to iterate through a JSON array?
I receive an array of objects:
[{json object},{json object},{json object}]
What is the simplest piece of code I could use to access the JSONObjects in the array?
EDIT: now that I think of it the method I used to iterate the loop was:
for (String row: json){
id = row.getInt("id");
name = row.getString("name");
password = row.getString("password");
}
So I guess I had was somehow able to turn the returned Json into and iterable array. Any Ideas how I could achieve this?
I apologise for my vaguness but I had this working from an example I found on the web and have since been unable to find it.
I think this code is short and clear:
int id;
String name;
JSONArray array = new JSONArray(string_of_json_array);
for (int i = 0; i < array.length(); i++) {
JSONObject row = array.getJSONObject(i);
id = row.getInt("id");
name = row.getString("name");
}
Is that what you were looking for?
I have done it two different ways,
1.) make a Map
HashMap<String, String> applicationSettings = new HashMap<String,String>();
for(int i=0; i<settings.length(); i++){
String value = settings.getJSONObject(i).getString("value");
String name = settings.getJSONObject(i).getString("name");
applicationSettings.put(name, value);
}
2.) make a JSONArray of names
JSONArray names = json.names();
JSONArray values = json.toJSONArray(names);
for(int i=0; i<values.length(); i++){
if (names.getString(i).equals("description")){
setDescription(values.getString(i));
}
else if (names.getString(i).equals("expiryDate")){
String dateString = values.getString(i);
setExpiryDate(stringToDateHelper(dateString));
}
else if (names.getString(i).equals("id")){
setId(values.getLong(i));
}
else if (names.getString(i).equals("offerCode")){
setOfferCode(values.getString(i));
}
else if (names.getString(i).equals("startDate")){
String dateString = values.getString(i);
setStartDate(stringToDateHelper(dateString));
}
else if (names.getString(i).equals("title")){
setTitle(values.getString(i));
}
}
Unfortunately , JSONArray doesn't support foreach statements, like:
for(JSONObject someObj : someJsonArray) {
// do something about someObj
....
....
}
When I tried #vipw's suggestion, I was faced with this exception:
The method getJSONObject(int) is undefined for the type JSONArray
This worked for me instead:
int myJsonArraySize = myJsonArray.size();
for (int i = 0; i < myJsonArraySize; i++) {
JSONObject myJsonObject = (JSONObject) myJsonArray.get(i);
// Do whatever you have to do to myJsonObject...
}
If you're using the JSON.org Java implementation, which is open source, you can just make JSONArray implement the Iterable interface and add the following method to the class:
#Override
public Iterator iterator() {
return this.myArrayList.iterator();
}
This will make all instances of JSONArray iterable, meaning that the for (Object foo : bar) syntax will now work with it (note that foo has to be an Object, because JSONArrays do not have a declared type). All this works because the JSONArray class is backed by a simple ArrayList, which is already iterable. I imagine that other open source implementations would be just as easy to change.
On Arrays, look for:
JSONArray menuitemArray = popupObject.getJSONArray("menuitem");
You are using the same Cast object for every entry.
On each iteration you just changed the same object instead creating a new one.
This code should fix it:
JSONArray jCastArr = jObj.getJSONArray("abridged_cast");
ArrayList<Cast> castList= new ArrayList<Cast>();
for (int i=0; i < jCastArr.length(); i++) {
Cast person = new Cast(); // create a new object here
JSONObject jpersonObj = jCastArr.getJSONObject(i);
person.castId = (String) jpersonObj.getString("id");
person.castFullName = (String) jpersonObj.getString("name");
castList.add(person);
}
details.castList = castList;
While iterating over a JSON array (org.json.JSONArray, built into Android), watch out for null objects; for example, you may get "null" instead of a null string.
A check may look like:
s[i] = array.isNull(i) ? null : array.getString(i);

Categories