How to access elements in java subarray without key but with index - java

I have an JSON that looks like this:
{ "Message": "None", "PDFS": [
[
"test.pdf",
"localhost/",
"777"
],
[
"retest.pdf",
"localhost\",
"666"
] ], "Success": true }
I'm trying to access the individual strings within the arrays but I'm having difficulty doing it as getString is requiring me to use a key and not indexes.
I've tried this to access the first string in each sub-array:
JSONArray pdfArray = resultJson.getJSONArray("PDFS");
for (int i = 0; i < pdfArray.length(); i++) {
JSONObject pdfObject = pdfArray.getJSONObject(i);
String fileName = pdfObject.getString(0);
}

Read the array as an array:
JSONArray array = pdfArray.getJSONArray(i);
String fileName = array.getString(0);

Related

Parsing through JSON and selecting multiple items in java

I currently have this JSON:
[
{
"example": "12345678",
"test": "0",
"name": "tom",
"testdata": "",
"testtime": 1531209885613
},
{
"example": "12634346",
"test": "43223452234",
"name": "jerry",
"testdata": "pawenkls",
"testtime": 1531209888196
}
]
I am trying to parse through the array to find a value of "testdata" that matches the value of "testdata" that I have generated, which I am currently doing like so:
JsonArray entries = (JsonArray) new JsonParser().parse(blockchainJson);
JsonElement dataHash = ((JsonObject)entries.get(i)).get("dataHash");
Then I wish to find the value of "example" that is in the same array as the "testdata" with the value "pawenkls".
How do I search for the "example" value that is in the same group as the value of "test data" that I have found?
You need to run through the objects in the array and check the value of the testData field against yours. Then read its example field.
String testData = "pawenkls";
JsonArray entries = (JsonArray) new JsonParser().parse(blockchainJson);
String example = null;
for(JsonElement dataHashElement : entries) {
JsonObject currentObject = dataHashElement.getAsJsonObject();
if(testData.equals(currentObject.get("testdata").getAsString())) {
example = currentObject.get("example").getAsString();
break;
}
}
System.out.println("example: "+example);
This prints out
example: 12634346
Here is a Java 8 version doing the same thing:
String testData = "pawenkls";
JsonObject[] objects = new Gson().fromJson(blockchainJson, JsonObject[].class);
Optional<JsonObject> object = Arrays.stream(objects)
.filter(o -> testData.equals(o.get("testdata").getAsString()))
.findFirst();
String example = null;
if(object.isPresent())
example = object.get().get("example").getAsString();
System.out.println("example: "+example);

Accessing elements in JSON array

I haven't worked much with JSON and I'm using Google Maps Distance Matrix API to get generate some data I'd like to use.
I'd like to pull the number 14147 from duration.
{
"destination_addresses" : [ "Washington, DC, USA" ],
"origin_addresses" : [ "New York, NY, USA" ],
"rows" : [
{
"elements" : [
{
"distance" : {
"text" : "226 mi",
"value" : 364089
},
"duration" : {
"text" : "3 hours 56 mins",
"value" : 14147
},
"status" : "OK"
}
]
}
],
"status" : "OK"
}
I've tried a few different things, here's what I tried last (data is just the array above):
String data = getOutputAsText(geoService);
JSONObject json = new JSONObject(data);
String duration = json.getJSONArray("rows").getString("duration");
Here's the console output:
org.json.JSONException: JSONObject["duration"] not found
I made sure to look around before posting but I haven't found anything that has been able to help me with this particular problem.
I want to pass the value from duration to my own web service, which I can do, I just don't know how to extract the value. Thank you in advance!
First of all, please have a look at this answer. Using org.json you can do smth. like that:
JSONObject obj = new JSONObject("Content of your string here");
JSONArray rows = obj.getJSONArray("rows");
for (int i = 0; i < rows.length(); i++) {
JSONArray elements = rows.getJSONObject(i).getJSONArray("elements");
for(int j = 0; j < elements.length(); j++) {
JSONObject element = elements.getJSONObject(j);
JSONObject duration = element.getJSONObject("duration");
int value = duration.getInt("value");
}
}
The code above has produced following output using your json String: 14147
P.S. You can make use of a library you wish. This one used here was purposed for the demonstrating.

Android: Dynamically Get JSON Array Key Name From JSON

I have a json link, if we open it I get a following result
{
"Status": "Success",
"All_Details": [{
"Types": "0",
"TotalPoints": "0",
"ExpiringToday": 0
}],
"First": [{
"id": "0",
"ImagePath": "http://first.example.png"
}],
"Second": [{
"id": "2",
"ImagePath": "http://second.example.png"
}],
"Third": [{
"id": "3",
"ImagePath": "http://third.example.png"
}],
}
What I need is, I want to dynamically get all the key names like status, All_details, First etc.
And I also want to get the data inside the All_details and First Array.
I used following method
#Override
public void onResponse(JSONObject response) throws JSONException {
VolleyLog.d(TAG, "Home Central OnResponse: " + response);
String statusStr = response.getString("Status");
Log.d(TAG, "Status: " + statusStr);
if (statusStr.equalsIgnoreCase("Success")) {
Iterator iterator = response.keys();
while (iterator.hasNext()) {
String key = (String)iterator.next();
}
}
}
I get all the key names in get stored in the String key. But I am unable to open get the values inside the JSON array, for eg. I need to get the values inside first and second array using the String(Key). How can I do that.???
First, to get the keynames, you can easily iterate through the JSONObject itself as mentioned here:
Iterator<?> keys = response.keys();
while( keys.hasNext() ) {
String key = (String)keys.next();
if ( response.get(key) instanceof JSONObject ) {
System.out.println(key); // do whatever you want with it
}
}
Then, to get the values of the array:
JSONArray arr = response.getJSONArray(key);
JSONObject element;
for(int i = 0; i < arr.length(); i++){
element = arr.getJSONObject(i); // which for example will be Types,TotalPoints,ExpiringToday in the case of the first array(All_Details)
}
If you want to get the JSON array from the response JSONObject you can use the JSONArray class. JSONObject has a method to get a JSONArray: getJSONArray(String). Remember to catch the JSONException when trying this. This exception will be thrown if there is no key for example.
Your code could look like this (only the while loop):
while (iterator.hasNext()) {
String key = (String)iterator.next();
try {
JSONArray array = response.getJSONArray(key);
// do some stuff with the array content
} catch(JSONException e) {
// handle the exception.
}
}
You can get the values from the array with the methods of JSONArray (see the documentation)
Something like this will allow you to iterate on array and individual fields once you have extracted the keys using what you have done. Instead of "Types" use the key variable you will create before this.
JSONArray allDetails = response.getJsonArray("All_Details")
for (int i = 0 ; i < allDetails.length(); i++) {
JSONObject allDetail = allDetails.getJSONObject(i);
allDetails.getString("Types");
}
First of all I want to inform you that it's not a valid JSON. Remove the last Comma (,) to make it valid.
Then you can Iterate like here
JSONArray myKeys = response.names();
Try this one
Iterator keys = jsonObject.keys();
while (keys.hasNext()) {
try {
String dynamicKey = (String) keys.next();//Your dynamic key
JSONObject item = jsonObject.getJSONObject(dynamicKey);//Your json object for that dynamic key
} catch (JSONException e) {
e.printStackTrace();
}
}

Search for a particular item in place types in google map json data

I tried to find particular item types in JSON data.
Like
"types": [
"restaurant",
"food",
"lodging",
"point_of_interest",
"establishment"
],
"types": [
"meal_delivery",
"restaurant",
"food",
"point_of_interest",
"establishment"
],
Some times restaurant is coming in 0th position sometimes in 1st position.
How to find weather types contains "restaurant" or not
You need to iterate through the JSON Array of "types" and check whether it contains "restaurant" -
JSONObject obj = new JSONObject(jsonString);
JSONArray arr = obj.getJSONArray("types");
for (int i = 0; i < arr.length(); i++)
if("restaurant".equals(arr.get(i).toString())){
}
The response you are getting is jsonobject get the json array and compare with the required string
JSONObject jObj = new JSONObject(response);
JSONArray jAry= jObj.getJSONArray("types");
String str="restaurant";
for (int i = 0; i < arr.length(); i++){
if(str.equalsIgnoreCase(jAry.get(i).toString())){
//do whatever you want
}
}
it will work for you.
JSONObject jObj = new JSONObject(response);
JSONArray jsonArray= jObj.getJSONArray("types");
boolean s = false;
if (s==jsonArray.toString().contains("restaurant"))
{
}

Parse JSON Array

My JSON is something like this:
[{
"myviews":[{
"2011-05-12_2011-05-14":{
"name":"thiswk",
"data":[[12,
2403
],
[13,
2082
],
[14,
5823
]
]
}
},
{
"2011-06-05_2011-06-7":{
"name":"lastwk",
"data":[[5,
1279
],
[6,
6685
],
[7,
2163
]
]
}
}
]
}
]
JSONObject jo = new JSONObject(jsonString);
JSONArray ja;
jo = jo.getJSONObject("2011-05-12_2011-05-14");
ja = jo.getJSONArray("data");
int resultCount = ja.length();
for (int i = 0; i < resultCount; i++)
{
JSONObject resultObject = ja.getJSONObject(i);
resultObject.getJSONArray("12");
System.out.println("--");
}
I am unable to read the values under the "data" array. Get this error
Exception in thread "main"
org.json.JSONException: A JSONObject
text must begin with '{' at character
1
You're trying to create a JSONObject based on a string that doesn't represent an object, but an array containing one object.
To get the contained object, try
JSONArray inputArray = new JSONArray(jsonString);
JSONObject jo = inputArray.getJSONObject(0);
I think some of your later work is wrong as well, but perhaps this will get you started.
data appears to be an array of arrays. Perhaps you need to call ja.getJSONArray(i)?

Categories