How to combine two JSONArrays JAVA (special requirements below) - java

I have a code snippet to combine two JSONArrays into one. Here it is,
for (i = 0; i < cityJArray.length(); i++)
{
resultsJArray.put(cityJArray.getJSONObject(i));
}
It works as it adds the second JSONArray (cityJArray) to the first (resultsJArray). But, my requirement is to add the second one to the first array of the first JSONArray (apologies for I'm not able to explain by words, but I will try to explain using codes down).
This is the JSONObject:
{"results":
[{"id": 248,
"name": "Alternatif Cibubur",
"slug": "alternatif-cibubur",
"status": "active",
"city":
{"id": 11,
"name": "Depok",
"slug": "depok",
},
"longitude": 106.900786}]}
I have already converted it into JSONArray because I have to separate the field 'city' and change its attribute names into 'city_id', 'city_name', 'city_slug'. Because they will create a duplicate as it's already an attribute at 'results' field (see the given JSONObject).
(Purpose: Create a .CSV file from JSONObject)
(Problem begins: When I try to seperate a field from the JSONObject to make it into different columns)
JSONArrays details:
resultsJArray:
[{"id": 248,
"name": "Alternatif Cibubur",
"slug": "alternatif-cibubur",
"status": "active",
"longitude": 106.900786}]
cityJArray:
[{"id": 11,
"name": "Depok",
"slug": "depok"
}]
I want to add this two seperated JSONArrays into one like this (below is the expected output)
[{"id": 248,
"name": "Alternatif Cibubur",
"slug": "alternatif-cibubur",
"status": "active",
"longitude": 106.900786,
"city_id": 11,
"city_name": "Depok",
"city_slug": "depok"}]

This should work as required, I have noted both arrays as Strings initially then converted both to JSONArray.
String resultsString = "[{ 'id': 248, 'name': 'Alternatif Cibubur', 'slug': 'alternatif-cibubur', 'status': 'active', 'longitude': 106.900786 }]";
String cityString = "[{ 'id': 11, 'name': 'Depok', 'slug': 'depok' }]";
try
{
//Convert String into JSONArray for both results and city.
JSONArray resultsJArray = new JSONArray(resultsString);
JSONArray cityJArray = new JSONArray(cityString);
//Get the first and only JSONObject within each of the arrays.
JSONObject resultsJObject = resultsJArray.getJSONObject(0);
JSONObject cityJObject = cityJArray.getJSONObject(0);
//Get the required values from the JSONObject within city.
int city_id = cityJObject.getInt("id");
String city_name = cityJObject.getString("name");
String city_slug = cityJObject.getString("slug");
//Put the values into the results JSONObject.
resultsJObject.put("city_id", city_id);
resultsJObject.put("city_name", city_name);
resultsJObject.put("city_slug", city_slug);
//Print to verify.
System.out.println("Updated resultsJArray: " + resultsJArray);
}
catch (JSONException e)
{
e.printStackTrace();
}

I use the package "com.alibaba.fastjson" , code as follow:
public static void CombinTest(){
String a = "[{\"id\": 248, \n" +
"\"name\": \"Alternatif Cibubur\", \n" +
"\"slug\": \"alternatif-cibubur\", \n" +
"\"status\": \"active\", \n" +
"\"longitude\": 106.900786}]";
String b = "[{\"id\": 11, \n" +
"\"name\": \"Depok\", \n" +
"\"slug\": \"depok\"\n" +
"}]";
JSONArray resultObjArr = JSON.parseArray(a);
JSONArray cityObjArr = JSON.parseArray(b);
for (int i = 0; i < resultObjArr.size(); i++)
{
JSONObject city = cityObjArr.getJSONObject(i);
Set<String> keys = city.keySet();
if(keys.size()>0){
for(String key:keys){
resultObjArr.getJSONObject(i).put("city_"+key,city.get(key));
}
}
}
System.out.println(JSON.toJSONString(resultObjArr));
}

Related

Parsing JSONObject to access ID when there are multiple ID values (Java)

I am obtaining a JSON response from an API that gives me a list of call records formatted as JSON. I want to parse through the data and find the record ID, my trouble is that each JSON record has multiple ID's and I am not sure how to access the correct one. Keep in mind, I do not know the value of the ID is "3461487000073355176" prior to running the request.
This is my code to receive the JSON, I created a JSONObject so I can hopefully store the value.
1.
Response response = client.newCall(request).execute();
String responseBody = response.body().string();
Gson gson = new GsonBuilder().setPrettyPrinting().create();
JsonParser parser = new JsonParser();
JsonElement je = parser.parse(responseBody);
String prettyJsonString = gson.toJson(je);
JSONObject json = new JSONObject(prettyJsonString);
System.out.println("Json = " + json);
The JSON the ID I need to access has a comment next to it:
"data": [
{
"Owner": {
"name": "My namen",
"id": "346148700000017",
"email": "m#gmail.com"
},
"$state": "save",
"$process_flow": false,
"Street": "95## ### ######",
"id": "**3461487000073355176**", ----This is the ID I need -----
"Coverage_A_Dwelling": 100000,
"$approval": {
"delegate": false,
"approve": false,
"reject": false,
"resubmit": false
},
"Created_Time": "2020-12-10T09:05:17-05:00",
"Property_Details": "Primary Residence",
"Created_By": {
"name": "My name",
"id": "346148700000017",
"email": "m#gmail.com"
},
"Description": "Created on Jangl: https://jan.gl/crwp773ytg8",
"$review_process": {
"approve": false,
"reject": false,
"resubmit": false
},
"Property_State": "FL",
"Property_Street": "95",
"Roof_Material": "Asphalt Shingle",
"Full_Name": "Clare Em",
"Property_City": "Land ",
"Email_Opt_Out": false,
"Lead_I_D": "4FFEC0C5-FBA1-2463-DB9B-C38",
"Insured_1_DOB": "1942-02-20",
"$orchestration": false,
"Tag": [],
"Email": "cr#yahoo.com",
"$currency_symbol": "$",
"$converted": false,
"Zip_Code": "338",
"$approved": true,
"$editable": true,
"City": "Land O Lakes",
"State": "FL",
"Structure_Type": "Single Family",
"Prior_Carrier": {
"name": "Default Carrier (DO NOT DELETE OR CHANGE)",
"id": "3461487000000235093"
},
"Source": {
"name": "EverQ",
"id": "346148700006474"
},
"First_Name": "Clarence",
"Modified_By": {
"name": "My name",
"id": "3461487000000172021",
"email": "m#gmail.com"
},
"Phone": "7036159075",
"Modified_Time": "2020-12-10T09:05:17-05:00",
"$converted_detail": {},
"Last_Name": "####",
"$in_merge": false,
"$approval_state": "approved",
"Property_Zip": "34638"
}
],
"info": {
"per_page": 200,
"count": 1,
"page": 1,
"more_records": false
}
}
If I understood it correctly, you can get the id like this:
Here, json has the following value.
[
{
"Owner": {
"name": "My namen",
"id": "346148700000017",
"email": "m#gmail.com"
},
"id": "**3461487000073355176**"
...
}
]
Now I can iterate over JSONArray to get the id.
JSONArray jsonArray = new JSONArray(json);
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObject = (JSONObject) jsonArray.get(i);
String id = (String) jsonObject.get("id");
System.out.println(id);
}
It prints out **3461487000073355176**.
You can do jsonObject.getJSONArray("data"); in your example to obtain JSON array.
The posted JSON response is missing the initial "{".
Your JSON contains data, which is a JSONArray of Owner objects. To get the id field of the first owner (array element 0):
// existing code
JSONObject json = new JSONObject(prettyJsonString);
System.out.println("Json = " + json);
// get the id field
JSONArray dataArray = (JSONArray)json.get("data");
JSONObject data0 = (JSONObject) dataArray.get(0);
JSONObject owner = (JSONObject) data0.get("Owner");
String id = owner.getString("id");
System.out.println(id);
Not sure if understood correctly but if you need to get all the IDs in that "level" why don't you try to model it as a class instead of using parser and let Gson do the parsing (this class might be useful later if you need to add more details)?
For example, defining something like this:
#Getter #Setter
// This models the response string from body
public class Response {
#Getter #Setter
// This models objects in the data list/array
public static class IdHolder {
// Only id because not interested of the rest
private String id;
}
// Only list of id holders because not interested of the rest
private List<IdHolder> data;
}
Then it would be as easy as:
Response res = gson.fromJson(responseBody, Response.class);
// Print out what you got
res.getData().stream().map(IdHolder::getId).forEach(System.out::println);

Reading the desired field from the JSON which is neither JSONobject nor JSONArray in Java and MongoDB Integration

I want to read the list of friend from the following JSON in java. My java code sample is shown in the post when i execute the below code the error is either friend is not found or its not array/object. Any help is appreciated. I tried many combinations of the code. For the details the JSON is basically the collection of the Mongodb having one user record.
My JSON:
{
"_id":{
"$oid":"5de5266f63b6a8fbb9eb79be"
},
"ename":[
"A_Jahoor"
],
"twitter":{
"name":[
"test"
],
"screen_name":[
"Jhoor"
],
"location":[
"islamabad pakistan"
],
"created time":[
"Sat Dec 29 16:55:43 +0000 2012"
],
"language":[
null
],
"friends":{
"name":[
"Bikas",
"Jebran Khan",
"Bimal Subedi\ud83c\uddf3\ud83c\uddf5",
"Web Developer",
"June Hunt",
"IJA-ERA",
"Faseeh Ullah",
"Engr Lukman",
"Kamran Ali",
"Iftikhar Ahmad",
"Ahmed-i Konevi",
"tanveer butt",
"Malik Abrar \ud83c\uddf5\ud83c\uddf0",
"Engr Waqas",
"yasir khan"
],
"location":[
"Nepal",
"",
"Seoul,South Korea",
"palandri,Azad Kashmir,Pakistan",
"",
"India",
"",
"Peshawar, Pakistan",
"",
"Islamabad, Pakistan",
"Istanbul, Turkey",
"Punjab, Pakistan",
"Islamabad, Pakistan",
"Peshawar, Pakistan",
""
],
"statuses":[
33,
85,
4102,
1,
1,
171,
9,
2,
3,
38,
7481,
234,
2467,
17,
1
]
}
}
}
My Java Code
String pageName = jsnobject.getJSONObject("_id").getString("$oid");
System.out.println(pageName);
JSONArray arr = jsnobject.getJSONArray("friends");
for (int i = 0; i < arr.length(); i++) {
String post_id = arr.getJSONObject(i).getString("name");
System.out.println(post_id);
}
The following code has solved my problem.
String job=((org.bson.Document) it.next()).toJson();
JSONObject jsnobject = new JSONObject(job);
List<String> list = new ArrayList<String>();
// System.out.println(job);
JSONArray jsonArray = jsnobject.getJSONArray("ename");
String pageName = jsnobject.getJSONObject("_id").getString("$oid");
JSONArray syncresponse = jsnobject.getJSONObject("twitter").getJSONArray("name");
JSONArray syncresponse1 = jsnobject.getJSONObject("twitter").getJSONArray("location");
JSONObject syncresponse2 = jsnobject.getJSONObject("twitter");
JSONArray syncresponse3=syncresponse2.getJSONObject("friends").getJSONArray("name");
System.out.println("User Name:"+syncresponse);
System.out.println("User Location:"+syncresponse1);
// System.out.println(syncresponse2);
System.out.println("User FriendsList:"+syncresponse3);

how to get elements from JSONObject and write it to file

i have a following JSONObject
{"elements": [
{
"name": "StartLabelFormat",
"value": "^XA"
},
{
"name": "shipperAddressLine1",
"value": "Street1",
"format": {"Text": {
"orientation": "N",
"height": "28",
"width": 20,
"fontname": 0,
"y": 373,
"x": 20
}}
},
{
"name": "EndLabelFormat",
"value": "^XZ"
}
]}
Now i want to get element from this Object and write it to a file.
For Example, for this block
{
"name": "shipperAddressLine1",
"value": "Street1",
"format": {"Text": {
"orientation": "N",
"height": "28",
"width": 21,
"fontname": 0,
"y": 373,
"x": 20
}}
},
I want to write in file as
^FT 20, 373 ^A0N, 28, 21 ^FDStreet1^FS.
Please help me to do this.
How to do it ?
If you meet {} in your code , you can use JSONObject to parse it .
If you meet [] in your code , you can use JSONArray to parse it .
And if you meet [] in your code , you can use for loop to get value in it .
And you should use try catch in your code .
Try this in your code .
try {
JSONObject jsonObject = new JSONObject(response);
JSONArray elements = jsonObject.getJSONArray("elements");
for (int i = 0; i < elements.length(); i++) {
JSONObject jsonObject1 = elements.getJSONObject(i);
String name = jsonObject1.optString("name");
String value = jsonObject1.optString("value");
JSONObject format = jsonObject1.optJSONObject("format");
JSONObject Text = format.optJSONObject("Text");
String orientation = Text.optString("orientation");
String height = Text.optString("height");
String width = Text.optString("width");
}
} catch (JSONException e) {
e.printStackTrace();
}
Note
And use optString and optJSONObject in your code . If format is null ,it will not return error .
And you can judge that JSONArray's length is not 0 and not null in the code .
To get this element from JsonArray
JsonObject yourElement = yourJsonArray.get(index);
Simply, you can use gson library for parsing json to objects.
public class Staff {
private String name;
private String value;
//...
and use Gson
String jsonInString = " {
"name": "shipperAddressLine1",
"value": "Street1"
}";
Staff staff = gson.fromJson(yourElement.toString() , Staff.class);
After that you can write in file by using your custom toString() method inside Staff class.
P.S. to convert JsonObject to String you can use also toString() method.

How to access JSON data with multiple array objects : android

I am stuck in getting the data from the JSON file with multiple data sets.
{
"status": "ok",
"count": 3,
"count_total": 661,
"pages": 133,
"posts": [
{
"id": 20038,
"type": "post",
"slug": "xperia-launcher-download",
"url": "http:\/\/missingtricks.net\/xperia-launcher-download\/",
"status": "publish",
"title": "Download Xperia Launcher app for Android (Latest Version)"
},
{
"id": 94,
"type": "post",
"slug": "top-free-calling-apps-of-2014-year",
"url": "http:\/\/missingtricks.net\/top-free-calling-apps-of-2014-year\/",
"status": "publish",
"title": "Best Free Calling Apps for Android November 2014"
},
{
"id": 98,
"type": "post",
"slug": "top-free-calling-apps-of-2016-year",
"url": "http:\/\/missingtricks.net\/top-free-calling-apps-of-2016-year\/",
"status": "publish",
"title": "Best Free Calling Apps for Android December 2016"
}
]
}
I need to access the title, url and status from the above JSON file.
#Override
protected void onPostExecute(String result) {
//this method will be running on UI thread
pdLoading.dismiss();
List<DataFish> data = new ArrayList<>();
pdLoading.dismiss();
try {
JSONArray jArray = new JSONArray(result);
// Extract data from json and store into ArrayList as class objects
for (int i = 0; i < jArray.length(); i++) {
JSONObject json_data = jArray.getJSONObject(i);
DataFish fishData = new DataFish();
fishData.status = json_data.getString("status");
fishData.title = json_data.getString("url");
fishData.sizeName = json_data.getString("title");
data.add(fishData);
}
} catch (JSONException e) {
Toast.makeText(JSonActivity.this, e.toString(), Toast.LENGTH_LONG).show();
Log.d("Json","Exception = "+e.toString());
}
}
I am getting a JSONException with the above code.
What should I do to access the title,status and url from the JSON File?
You have to fetch your JSONArray which is inside a JSONObject , so create a JSONObject and fetch your array with index "posts"
1.) result is a JSONObject so create a JSONObject
2.) Fetch your JSONArray with index value as "posts"
3.) Now simply traverse array objects by fetching it through index
JSONObject jObj = new JSONObject(result);
JSONArray jArray = jObj.getJSONArray("posts");
// Extract data from json and store into ArrayList as class objects
for (int i = 0; i < jArray.length(); i++) {
JSONObject json_data = jArray.getJSONObject(i);
DataFish fishData = new DataFish();
fishData.status = json_data.getString("status");
fishData.title = json_data.getString("url");
fishData.sizeName = json_data.getString("title");
data.add(fishData);
}
Note : i don't know weather it is a sample response with shorter version though your json object should ends with } not with , .
[{"id":20038,"type":"post","slug":"xperia-launcher-download","url":"http://missingtricks.net/xperia-launcher-download/","status":"publish","title":"Download
Xperia Launcher app for Android (Latest Version)",
// ^^^ there should be a } not a , to end json
// so make sure to do the correction so it will look like => ...st Version)"},
{"id":94,"type":"post","slug":"top-free-calling-apps-of-2014-year","url":"http://missingtricks.net/top-free-calling-apps-of-2014-year/","status":"publish","title":"Best
Free Calling Apps for Android November 2014", ]
Improvements :
you can use optString to avoid null or non-string value if there is no mapping key
This has two variations
Get an optional string associated with a key. It returns the
defaultValue if there is no such key.
public String optString(String key, String defaultValue) {
fishData.status = json_data.optString("status","N/A");
// will return "N/A" if no key found
or To get empty string if no key found then simply use
fishData.status = json_data.optString("status");
// will return "" if no key found where "" is an empty string
You can validate your JSON here.
If entire JSON getJsonObject() is not working, then you should parse JSON objects & array in multiple arrays then use them.

how to retrieve JSON object from the JSON array

I am having the below JSON. Inside this JSON I am having "ticketDetails" as JSON array. From this array I want to retrieve the value of ticketPrice inside the json object "amount". How can I do that?
{
"ticketDetails": [{
"seq": 1,
"qty": 2,
"amount": {
"ticketPrice": 120,
"bookingFee": 50
},
"session": {
"id": 1001,
"date": "2013, 9, 15",
"time": "1300"
},
"venue": {
"id": "MTRG",
"name": "Adlabs Manipur",
"companyCode": "ADLB"
},
"event": {
"id": "ET00000001123",
"name": "Chennai Express",
"producerCode": "YRF"
},
"category": {
"ttypeCode": "00012",
"areaCatCode": "2414",
"type": "Gold",
"price": 270
}
}]
}
Any suggestion will helpful...
Below is the sample code for retrieving the ticketPrice from the given JSONObject:
JSONObject objData = (JSONObject)JSONSerializer.toJSON(data);
JSONArray objTicketDetailsJsonArr = objData.getJSONArray("ticketDetails");
for(int nSize=0; nSize < objTicketDetailsJsonArr.size(); nSize++){
String ticketPrice = "";
ticketPrice = objTicketDetailsJsonArr.getString("ticketPrice");
}
Below are the imports for the above code:
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import net.sf.json.JSONSerializer;
source of JAR: http://json-lib.sourceforge.net/
you store your data within a variable
data = {...}
then you access it this way:
data.ticketDetails[0].amount.ticketPrice
if the ticketDetails have more than one element
you can loop over the ticketDetails array and store all the ticketPrice values within an other array, ticketPriceArray
the following would work fine in JavaScript:
var ticketPriceArray = data.ticketDetails.map(function(k){
return k.amount.ticketPrice;
});
if you are using another programming language a general loop would work fine also
for ( i; i< ticketDetails.length ; i++){
ticketPriceArray[i] = data.ticketDetails.amount.ticketPrice[i];
}
For Java check this tutorial:
http://answers.oreilly.com/topic/257-how-to-parse-json-in-java/
you can try this code:
JsonObject transactiondata = (JsonObject)Offer.get("transData");
JsonObject ticketdata = (JsonObject)transactiondata.get("tickets");
JsonObject offerData = (JsonObject)Offer.get("offerData");
JsonObject offerData1 = (JsonObject)offerData.get("offerconfig");
JsonArray jsonarr= (JsonArray)ticketdata.get("ticketDetails");
double ticketPrice = Double.parseDouble(jsonarr.get(0).getAsJsonObject().get("amount").getAsJsonObject().get("ticketPrice").getAsString());
System.out.println("ticketPrice:"+ticketPrice);

Categories