Jesse Lukas Jesse Lukas - 1 month ago 7
Java Question

Two JsonArray`s Compairing missing keys

Hello a small Question i have 2 JsonArrays with datas from API

Api 1

[{"id":1,"value":270},{"id":2,"value":1432493},{"id":3,"value":63},{"id":5,"value":412},{"id":6,"value":371},{"id":7,"value":824},{"id":9,"value":266}]


Api 2

[{"id":1,"name":"name","description":"description"},{"id":2,"name":"name","description":"description"},{"id":3,"name":"name","description":"description"},{"id":4,"name":"name","description":"description"},{"id":5,"name":"name","description":"description"},{"id":6,"name":"name","description":"description"},{"id":7,"name":"name","description":"description"},{"id":8,"name":"name","description":"description"},{"id":9,"name":"name","description":"description"}]


i will Cambine it to new array

JSONArray jArray = new JSONArray(API1);
JSONArray jArray1 = new JSONArray(API2);

for(int i=0;i<jArray1.length();i++) {
JSONObject json_data = jArray.getJSONObject(i);
JSONObject json_data1 = jArray1.getJSONObject(i);
DataWallet walletData = new DataWallet();
if (json_data.getString("id").equals(json_data1.getString("id"))) {
walletData.wallet_id = json_data.getString("id");
walletData.textWalletNumber = json_data.getString("value");
walletData.wallet_name = json_data1.getString("name");
walletData.wallet_desc = json_data1.getString("description");

} else {
walletData.wallet_id = json_data1.getString("id");
walletData.textWalletNumber = "0";
walletData.wallet_name = json_data1.getString("name");
walletData.wallet_desc = json_data1.getString("description");

}
data.add(walletData);

}


Now have i the problem
1,2,3 work fine by 4 is the problem from API1 give no entrys for value with "0" i will ad this over codes but this work not.

Thanks for Help :-)

Answer

You need also a second for loop inside the the first one (jArray1) to iterate over the jArray. Altogether you need two for loops to combine 2 arrays. If you have a really huge arrays its a good idea to use better algorithms e.g. Binary search. It makes it faster and more optimal for O.