Read the all value presents in Hashmap - java

I have define List of HashMap and reading the response of JSON API . Currently able to read only one value from the list and I want to read all the values.
List<HashMap<String,Object>> allids = response.jsonPath().getList("data");
HashMap<String,Object> firstid = allids.get(0);
Object a = firstid.get("country");
System.out.println(a);
JSON Response in PostMan
{
"response": {
"code": 200,
"status": "success",
"alert": [
{
"message": "Success",
"type": "success",
"skippable": 1
}
],
"from_cache": 0,
"is_data": 1
},
"data": [
{
"id": 6004,
"airport_name": "Adampur Airport",
"city": "Adampur",
"country": "India",
"iata": "AIP",
"icao": "VIAX",
"latitude": "31.4338",
"longitude": "75.758797",
"altitude": "775"
}
]
}

Just forEach on your List you will get Map and then get all your Object bu using get .
List<HashMap<String,Object>> allids = response.jsonPath().getList("data");
allids.forEach(elem->{
String country = (String) elem.get("country");
String city = (String) elem.get("city");
// and so on.
});

Judging from the context, you can iterate over the list and get the Map values
List<HashMap<String,Object>> allids = response.jsonPath().getList("data");
for(int i=0; i<allids.size(); i++){
HashMap<String,Object> firstid = allids.get(i);
String country = (String) firstid.get("country");
String city = (String) firstid.get("city");
String iata = (String) firstid.get("iata");
String altitude = (String) firstid.get("altitude");
//similarly get others
System.out.println(country);
}

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);

how to covert JSONObject to another Required JSONObect by mapping AccountId using java

**My result of JSONObject to convert as follows bellow code and have searched for many this how to convert using java but I converted that **
{
"result": {
"accountnames": [{
"accountName": "Hari",
"accountId": 878488
}, {
"accountName": "ravi",
"accountId": 878487
}],
"sales": [{
"accountSales": "89",
"accountId": 878488
}, {
"accountName": "98",
"accountId": 878487
}],
"countResult": [{
"accountResult": "945",
"accountId": 878488
}, {
"accountResult": "9452",
"accountId": 878489
}]
}
}
*and this is where the sample code to be converted *
{
"result": [{
"accountName": "Hari",
"accountSales": "89",
"accountResult": "945",
"accountId": 878488
},
{
"accountName": "ravi",
"accountSales": "98",
"accountId": 878487
},
{
"accountResult": "9452",
"accountId": 878489
}
]
}
My required JSON data has to be formatted as below
You need to group all the elements by accountId. You can use something like this depending on the json library that you are using.
Initialize the json object:
JSONObject rootJson = new JSONObject(json);
JSONObject resultJson = rootJson.getJSONObject("result");
Create a map to hold the objects by accountId:
Map<String, JSONObject> accountIds = new HashMap<>();
Then iterate for each key in the json, then for each element in the arrays and then for each property of the object inside the json:
Iterator mainKeys = resultJson.keys();
while (mainKeys.hasNext()) {
String key = (String) mainKeys.next();
JSONArray array = resultJson.getJSONArray(key);
for (int index = 0; index < array.length(); index++) {
JSONObject object = array.getJSONObject(index);
if (object.has("accountId")) {
String accountId = object.get("accountId").toString();
JSONObject accum = accountIds
.computeIfAbsent(accountId, (k) -> new JSONObject());
// depending on the json impl you can use putAll or similar
Iterator objKeys = object.keys();
while (objKeys.hasNext()) {
String property = (String) objKeys.next();
accum.put(property, object.get(property));
}
} else {
// does not have account id, ignore or throw
}
}
}
Finally create the json file and add the elements to the JSONArray:
JSONObject finalJson = new JSONObject();
finalJson.put("result", new JSONArray(accountIds.values()));
System.out.println(finalJson.toString());
(note: the json has an error in sales array accountName instead of accountSales)

get json data based on object name

May be it's a simple task for some one.
I've json like below.
{
"address": {
"state": "World",
"address": "infinite space, 000",
"city": "Android city",
"address2": {
"state": "World2",
"address": "infinite space2, 002",
"city": "Android city2",
"address3": {
"state": "World3",
"address": "infinite space3, 003",
"city": "Android city3"
}
}
},
"valid": {
"state": "World",
"address": "infinite space, 000",
"city": "Android city",
"valid2": {
"state": "World2",
"address": "infinite space2, 002",
"city": "Android city2",
"valid3": {
"state": "World3",
"address": "infinite space3, 003",
"city": "Android city3"
}
}
}
}
This is a sample structure. Some times may have many objects inside of one object. I know this is a bad format of JSON but i've to achieve my requirement by using this only :-(.
My requirement is: when we sending the object name like address3 or valid3 to a method as argument. My method have to return key and value of object (Which we passed as argument). Any one know, how to achieve this in Java?
You can parse the JSON and convert the result into a HashMap<String,String>
Here is sample code for this JSON object .
public HashMap<String,String> getKeyValuePairs(JSONObject json,String key){
HashMap<String,String> jsonHashList=new HashMap<String,String>();
JSONObject desiredJSON = json.get(key);
Iterator<?> keys = desiredJSON.keys();
while( keys.hasNext() ) {
String key2 = (String)keys.next();
if ( desiredJSON.get(key2) instanceof JSONObject ) {
String value = desiredJSON.get(key2);
jsonHashList.add(key2,value);
}
}
return jsonHashList;
}
Note : In this case key is assumed to be at level one of passed JSON so if you want to pass any JSON to get it's key values separated pass the Level One JSON.
This is the solution
private void parseJson(JSONObject jsonObject, String objName){
try {
for(int i = 0; i < jsonObject.length(); i++){
if(jsonObject.get(jsonObject.names().getString(i)) instanceof JSONObject){
JSONObject singleObj = new JSONObject(jsonObject.get(jsonObject.names().getString(i)).toString());
Iterator<String> keys= singleObj.keys();
while (keys.hasNext()){
String keyValue = keys.next();
final String valueString = singleObj.getString(keyValue);
if(!isJSONObjectOrString(valueString)){
if(keyValue.contains(objName) || valueString.contains(objName)
|| jsonObject.names().getString(i).contains(objName)){
Log.e("objectName", jsonObject.names().getString(i));
Log.e(keyValue, valueString);
}
}
}
parseJson(singleObj);
}
}
} catch (JSONException e) {
e.printStackTrace();
}
}

Issue In extracting desired data from the Json Response

My Json response looks like this:
{
"oAuthClientResponse": {
"grantTypes": [
"client_credentials",
"urn:ietf:params:oauth:grant-type:jwt-bearer"
],
"appId": "0e0da052-baab-4e86-a826-edfcaadbd93b",
"certAlias": "tenant_269869150664042.st2Oauth.st2Oauth_svc_269869150693042_st2_client_OAUTHCLIENT.cert",
"clientCertificate": "MIIC",
"paramList": null,
"audiences": [
"http://svc.com/EndPoint/st2/CommonApi::RW",
"http://svc.com/EndPoint/st2/CommonApi::RO"
],
"isDisabled": "false",
"clientMetadata": {
"isTenantManaged": "false",
"isTrusted": "true"
},
"activityData": {
"createdOn": "08/10/2015 02:15:55"
},
"tenant": "tenant_269869150664042",
"description": "st2Oauth_svc_269869150693042_st2_client_OAUTHCLIENT",
"name": "st2Oauth_svc_269869150693042_st2_client_OAUTHCLIENT",
"appSecret": "EghTRToAFJUWHrsnXlK5",
"clientType": "CONFIDENTIAL_CLIENT"
}
}
I want to read the value of audiences.
String value = jObject.getJSONObject("oAuthClientResponse").getString(
"audiences");
In value I am getting :
"audiences": [
"http://svc.com/EndPoint/st2/CommonApi::RW",
"http://svc.com/EndPoint/st2/CommonApi::RO"
]
Now I am not able to extract the value of the audiences.i.e.
http://svc.com/EndPoint/st2/CommonApi::RW and
http://svc.com/EndPoint/st2/CommonApi::RO
Kindly suggest.
Use getJSONArray() instead of getString()
JSONArray audiences = jObject.getJSONObject("oAuthClientResponse")
.getJSONArray("audiences");
Then you can retrieve the individual values using indices
System.out.println(audiences.getString(0)); // http://svc.com/EndPoint/st2/CommonApi::RW
System.out.println(audiences.getString(1)); // http://svc.com/EndPoint/st2/CommonApi::RO
String value = jObject.getJSONObject("oAuthClientResponse").getString(
"audiences");
value = value.subString(value.indexOf('['))
value = value.replace("[","");
value = value.replace("]","");
value = value.replace("\"","");
StringTokenizer stringTokenizer = new StringTokenizer(
actualOutput, ",");
while (stringTokenizer.hasMoreElements()) {
String value = (String) lineTokenizer.nextElement();
System.out.println(value)
}

How to fetch all the nodes and child nodes of JSON object in java?

I want to fetch all the nodes of the below JSON object. For example
result, identification, payment etc.
{
"result": {
"identification": {
"transactionid": "Merchant Assigned ID",
"uniqueid": "d91ac8ff6e9945b8a125d6e725155fb6",
"shortid": "0000.0005.6238",
"customerid": "customerid 12345"
},
"payment": {
"amount": "2400",
"currency": "EUR",
"descriptor": "order number"
},
"level": 0,
"code": 0,
"method": "creditcard",
"type": "preauthorization",
"message": "approved",
"merchant": {
"key1": "Value1",
"key0": "Value0"
}
},
"id": 1,
"jsonrpc": "2.0"
}
I have used the following code:
JSONObject partsData = new JSONObject(returnString);
Iterator<String> iterator = jsonObject.keys();
while (iterator.hasNext()) {
String result=iterator.next();
System.out.println(result);
}
But the result I am getting is:
id
result
jsonrpc
How do I get all the node names?
Move your iterator logic (to iterate over json) in a method
e.g.,
public Map<String,String> parse(JSONObject json , Map<String,String> out) throws JSONException{
Iterator<String> keys = json.keys();
while(keys.hasNext()){
String key = keys.next();
String val = null;
if ( json.getJSONObject(key) instanceof JSONObject ) {
JSONObject value = json.getJSONObject(key);
parse(value,out);
}
else {
val = json.getString(key);
}
if(val != null){
out.put(key,val);
}
}
return out;
}
This way you can check for each sub node in the json object.
You have to parse through all the objects.
JSONObject partsData = new JSONObject("result");
JsonObject identification = partsData.getJsonObject("identification");
JsonObject payment = partsData.getJsonobject("payment");

Categories