Read a specific value from JSON in Java - java

I am making an app in android studio using an API that returns the following:
[{"domains": ["upes.ac.in"], "country": "India", "state-province": "Dehradun", "web_pages": ["https://www.upes.ac.in/"], "name": "University of Petroleum and Energy Studies", "alpha_two_code": "IN"}]
I run it as follows:
public void onResponse(String response) {
listaUniversidades = new ArrayList<>();
JSONArray jsonArray = new JSONArray(response);
String nombreUni, pais, url;
for (int i = 0; i < jsonArray.length(); i++) {
nombreUni = jsonArray.getJSONObject(i).getString("name");
pais = jsonArray.getJSONObject(i).getString("country");
url = jsonArray.getJSONObject(i).getString("web_pages"));
texto.setText(url);
listaUniversidades.add(new Universidad(nombreUni, pais, url));
}}
The thing is that the web_pages returns the following: ["http://.www.upes.ac.in/"]
How could I make it return the correct url? Since that way I can not access the university website.
Thank you!

I will assume that you aways want to get the first "web_page" inside the "web_pages" array.
You can try to convert the "web_pages" attribute to an array before trying to get the first element, like this:
url = jsonArray
.getJSONObject(i)
.getJSONArray("web_pages"))
.getJSONObject(0)
.toString();

Have you verified that the API returns the expected value for web_pages? You can set a breakpoint on the line
String nombreUni, pais, url;
And then inspect the variable jsonArray. I think the incorrect value that you got is most likely because the API returns that value.

The problem is that "web_pages": ["https://www.upes.ac.in/"] is a JSON Array, so you need to convert it to the array and then access the appropriate item in it(presumably first one?)
It can be done the way Aleph proposed above.

Related

How iterate over the an API response and search for a particular string?

https://imgur.com/a/nJ4mFbs
I am new to using API's. The only thing I can currently do is search for a diagnostic report via ID by using the code:
DiagnosticReport dR = client.read().resource(DiagnosticReport.class).withId("3281").execute();
But how can I search to see if a subject with reference: "Patient/3250" exists, and if it exists, how can I return the string "Encounter/3267" from:
"context": { "reference": "Encounter/3267"
You can try this with JSON :-
JSONObject jsonObject = new JSONObject(JSON);
JSONObject getFirst = jsonObject.getJSONObject("Context");
Object level2 = getFirst.get("reference");
if(level2.equals("Patient/3250")){
System.out.println("True");
}
else{
System.out.println("False");
}
you can do the first part with a query. I'm not sure about the HAPI syntax for it, so I'll show it in a URL. Your query is
GET [base]/DiagnosticReport/3281
The query you want for searching to see if a subject with reference "Patient/3250" exists would be
GET [base]/DiagnosticReport?subject:Patient.id=3250

JSON index out of range

I'm currently trying to process some JSON but it's given me an error saying that "Index 0 out of range [0..0)" the affected line is the one that is commented out.
JSONObject parentObject3 = new JSONObject(finalJSON3);
JSONArray parentArray3 = parentObject3.getJSONArray("players");
//JSONObject finalObject3 = parentArray3.getJSONObject(0);
tempGameBans = finalObject3.getInt("NumberOfBans");
tempVacBans = finalObject3.getInt("NumberOfMutes");;
Here is my JSON:
{
"players": [
{
"userID": "5648131",
"NumberOfBans": 0,
"NumberOfMutes": 1,
}
]
}
Edit: Currently I am only looking for 1 object per JSON URL so the Index should always be 0, unlike the possible duplicate which seems to be looking for multiple objects.
Edit 2: I found out what the issue is and it's due to the JSON not being correctly sent from my server. Thanks for the help anyway guys.
String jsonString = new String("{\"players\": [{\"userID\": \"5648131\",\"NumberOfBans\": 0,\"NumberOfMutes\": 1}]}");
JSONObject parentObject3 = new JSONObject(jsonString);
JSONArray parentArray3 = parentObject3.getJSONArray("players");
JSONObject finalObject3 = parentArray3.getJSONObject(0);
System.out.println(finalObject3.getInt("userID"));
System.out.println(finalObject3.getInt("NumberOfBans"));
System.out.println(finalObject3.getInt("NumberOfMutes"));
This is working fine, so there has to be some another issue.
You are calling some attribute either not in the JsonObject or the attribute value at that specified index doesn't exist.
Try remove the "," at the end of "NumberOfMutes": 1,.

Parsing JSON in Java Using org.json

I have a large file with many JSON objects similiar to the following. I need to parse everything to get the "bought_together" items as an array using the org.json library. I'm having trouble accessing anything nested in "related".
What is the required code to retrieve "bought_together" as a list?
{
"asin": "11158732",
"title": "Girls Ballet Tutu Zebra Hot Pink",
"price": 3.17,
"imUrl": "http://ecx.images-amazon.com/images/I/51fAmVkTbyL._SY300_.jpg",
"related":
{
"also_bought": ["L00JHONN1S", "B002BZX8Z6"],
"also_viewed": ["F002BZX8Z6", "B00JHONN1S", "B008F0SU0Y", "B00D23MC6W", "B00AFDOPDA"],
"bought_together": ["D202BZX8Z6"]
},
"salesRank": {"Toys & Games": 211836},
"brand": "Coxlures",
"categories": [["Sports & Outdoors", "Other Sports", "Dance"]]
}
Here is my attempt (Please note, this is within a MapReduce program so some lines may seem out of context.):
JSONObject object = new JSONObject(sampleText); //sampleText is json that has been split by line
JSONArray boughtTogether = new JSONArray(object.getJSONArray("bought_together"));
using the following code, I hope it's help you.
//this will be your json object that contains and convert your string to jsonobject
//if you have json object already skip this.
JSONObject yourJSON = new JSONObject(targetString);
//getting the "related" jsonObject
JSONObject related = yourJSON.getJSONObject("related");
//getting the "bought_together" as an jsonArray and do what you want with it.
//you can act with jsonarray like an array
JSONArray bought_together = related.getJSONArray("bought_together");
//now if you run blow code
System.out.print(bought_together.getString(0));
//output is : D202BZX8Z6
-------update according to update the question------
you should change your code like this:
JSONObject object = new JSONObject(sampleText); //sampleText is json that has been split by line
JSONObject related = object.getJSONObject("related");
JSONArray boughtTogether = related.getJSONArray("bought_together");
-------update-------
i think you need to this point (it's not technicality all of they difference)
every thing are in {} , they will be JSONObject and the relation
is key and value like :
{"name":"ali"}
this is a jsonobject and the value of key "name" is ali and we call it
like:
myJsonObject.getString("name");
every thing are in [] ,they will be JSONArray and the relation is
index and value like :
["ali"]
this is a JsonArray the value of index 0 is ali and we call it
like:
myJsonArray.getString(0);
so in your case:
your total object is a JSONObject
the value of "related" key is still a JSONObject
the value of "bought_together" key (which is inside the value of {jsonobject} "related" key) is a JSONArray

Create JSON Array from List<Object> in Java

This is a basic Java question I think that I can't work out how to get around.
I get data from Google Analytics API and store the rows in my database as a string as a JSONArray
[["New Zealand","Auckland","1640","8.795731707317072","516.4469512195122"],["New Zealand","Wellington","1314","8.428462709284627","580.3302891933029"]]
For Google Maps I need a JSON Array:
function drawMap() {
var data = google.visualization.arrayToDataTable([
['City', 'Popularity'],
['New York', 200],
['Boston', 300],
['Miami', 400],
['Chicago', 500],
['Los Angeles', 600],
['Houston', 700]
]);
From https://developers.google.com/chart/interactive/docs/gallery/geomap
I need to change my data, by parsing it and iterating through it to remove the first (i.e. "New Zealand") and last variable from each object - I also need to add the headers i.e. ['City', 'Popularity']
Using GSonBuilder I can create JSON
[{"city":"Wellington","sessions":"1314","viewsPerSessions":"8.428462709284627","avgDuration":"8.428462709284627"},{"city":"Christchurch","sessions":"432","viewsPerSessions":"10.127314814814815","avgDuration":"10.127314814814815"}]
How do I turn that into a JSON Array?
I use the JSON parse of Android. With this you can get what you want.
Try this:
JSONArray js_data = [["New Zealand","Auckland","1640","8.795731707317072","516.4469512195122"],["New Zealand","Wellington","1314","8.428462709284627","580.3302891933029"]];
int lenght = js_data.length();
JSONArray city;
for(int i=0;i<length;i++) {
//get each city
city = js_data.getJSONArray(i);
String nameCity = city.getString(0);
String pop = city.getString(4);
//Create a object JSON or whatever you want with this data
JSONArray js_array = new JSONArray();
js_array.put(city); js_array.put(pop);
//And put on a list
js_map.put(js_array);
}
This is a basic java coding.
Hope it's helps.

How to parse this JSON string

I'm trying to parse this string into java, but I keep getting errors.
{"id":1,"jsonrpc":"2.0","result":{"limits":{"end":3,"start":0,"total":3},"sources":[{"file":"/media/storage/media/re Music/","label":"re Music"},{"file":"/media/storage/media/ra Music/","label":"ra Music"},{"file":"addons://sources/audio/","label":"Music Add-ons"}]}}
When I use this code ...
String temp = //json code returned from up above
JSONObject obj = new JSONObject(temp);
JSONArray array = obj.getJSONArray("sources");
I get an error saying org.json.JSONObject Value... and then displays what is in temp. Any help?
The array named "sources" is several levels deep. You need to traverse down into the json.
Code formatters help with this stuff...
http://jsonformatter.curiousconcept.com/
{
"id":1,
"jsonrpc":"2.0",
"result":{
"limits":{
"end":3,
"start":0,
"total":3
},
"sources":[
{
"file":"/media/storage/media/re Music/",
"label":"re Music"
},
{
"file":"/media/storage/media/ra Music/",
"label":"ra Music"
},
{
"file":"addons://sources/audio/",
"label":"Music Add-ons"
}
]
}
}
It looks like the "sources" array is in the "result" object. So you would need to get that object and then get the array from that like this:
JSONObject obj = new JSONObject(temp);
JSONObject result = obj.getJSONObject("result");
JSONArray array = result.getJSONArray("sources");
Your json should have top level object, from there you need to get child objects. See this link for more detail.

Categories