Android: json response, google api and getting image from url - android

I'm using google books api to get some data as json response.
in the response, there are JSONArrays, each element is a book and it contains data about it. the problem is the elements should be symmetric when it comes to the data they contain. in other words, each element should contain a title, authors, book cover url, rating and so on. and when a book doesn't contain ,for example, a rating, this value should exist and be empty but it doesn't exist at all for that element so in the for loop it throws an exception
so what should i do to avoid such a problem and i do need that data even if it's empty.
the other part is there is a url for the cover of the book provided in the response. i want to get that image. i tried both top answers in this link and non of them seemed to work.

Try to use optJSONObject instead of getJSONObject to get JSONObject.
Note: getJSONObject will through error if the object don't have the key, but optJSONObject will just return null if the object don't have value
JSONArray array = null;// your array
for (int i = 0; i < array.length(); i++) {
JSONObject jsonObject = array.optJSONObject(i);
if(jsonObject == null) {
continue;
}
// JSONObject ratingObject = jsonObject.getJSONObject("rating"); // Dont use this
JSONObject ratingObject = jsonObject.optJSONObject("rating");
if(ratingObject != null) {
// Do someting here
}
}
For Image loading you can use Glide lib it may help you.

Related

Json - how to parse a url in Android

I want to parse json from a url and use the json data with a listview.
I also want to only list the score and the name, but I have no idea how. Thanks.
{
"level":[
{
"id":1,
"server":[
{"score":33,"name":"Car"},
{"score":72,"name":"Bus"},
]
}
]
}
Do you know how to retrieve the data?
After you retrieve the data, parsing it is very simple. To get each individual item with its attributes I would use the following code:
String responseFromUrl;
JSONObject JSONResponse = new JSONObject(responseFromURL);
JSONArray level = JSONResponse.getJSONArray("level");
//The following loop goes through each object in "level". This is nessecary if there are multiple objects in "level".
for(int i=0; i<level.length(); i++){
JSONObject object = level.get(i);
int id = object.getInteger("id");
JSONArray server = object.getJSONArray("server");
//This second loop gets the score and name for each object in "server"
for(int j=0; j<server.length(); j++){
JSONObject serverObject = server.get(i);
int score = serverObject.getInteger("score");
String name = serverObject.getString("name");
}
}
Obviously replace "responseFromUrl" with the JSON response from the url in string format. If you don't know why I used JSONObject, JSONArray, String, Integer, etc., or are just confused about this, Udacity has a good course for making http connections and parsing JSON responses from APIs.
Link to Udacity Course
You can use the gson library to convert json to an java object
Download the latest jar and import into your project, currently you can download the latest at this link:
https://repo1.maven.org/maven2/com/google/code/gson/gson/2.8.1/gson-2.8.1.jar
After, this will help you:
https://stackoverflow.com/a/23071080/4508758
Hugs!

Iterate through Java jsonObjects without array included

My problem is that this will create 3 new instances of DailyJobObjects with the same values as object number one (01, Bill, 50). And it's logical that it would do so, so how can I iterate through my jsonObject so I can separate the three objects? I have looked this up tirelessly but everything thing I have seen has and array included in the jsonData which would make things easier but this response Body is coming straight from a database - no arrays, just back to back objects. Iterating only gives me keys which I already did in a separate method to give me one half of my map. Now I need the values. You don't have to give me an answer, you can (I rather) point to something I'm missing. Thanks!
{"id":"01","name":"Bill","salary":"50"},
{"id":"02","name":"James","salary":"60"},
{"id":"03","name":"Ethan","salary":"70"}
JSONObject fields = new JSONObject(jsonData);
mObjectArray = new DailyJobObjectArray[fields.length()];
for(int i=0; i< fields.length(); i++) {
DailyJobObject mObject = new DailyJobObject();
mObject.setName(fields.getString("name"));
mObject.setSalary(fields.getString("salary"));
mObjectArray[i] = mObject;
}
return mObjectArray;
As #Selvin has mentioned, your json is not valid. Either get proper json from the database or parse it in a non-standard way. I would suggest getting a proper json array from the DB.
String[] splitString = jsondata.split("[^a-zA-Z \\{\\}]+(?![^\\{]*\\})");
for ( String s : splitString) {
try {
JSONObject field = new JSONObject(s);
String name = field.getString("name");
String id = field.getString("id");
} catch (JSONException e) {
e.printStackTrace();
}
}
I also agree that your mObject(...) does not make sense at all
Maybe you're looking for something like this
mObject.setName(name)

Android Not Sure How To Refer To Value In JSON File (JSON Parsing)

Example JSON Page
http://maps.googleapis.com/maps/api/geocode/json?latlng=51.155455,-0.165058&sensor=true
#SuppressLint("NewApi")
public void readAndParseJSON(String in) {
try {
JSONObject reader = new JSONObject(in);
// This works and returns address
JSONArray resultArry = reader.getJSONArray("results");
String Address = resultArry.getJSONObject(1).getString("formatted_address").toString();
Log.e("Address", Address);
// Trying to get PostCode on code below - this is not working (log says no value at address components)
JSONArray postCodeArray = reader.getJSONArray("address_components");
String postCode = postCodeArray.getJSONObject(1).getString("long_name").toString();
Log.e("PostCode", postCode );
This code returns the address correctly. How can I get the post code long_name which is inside address_components?
Solution
I had to get each array, and then get the post code value.
I am using the value 7, as that is the JSONObject that has the postcode stored in the "long_name" field.
JSONObject readerJsonObject = new JSONObject(in);
readerJsonObject.getJSONArray("results");
JSONArray resultsJsonArray = readerJsonObject.getJSONArray("results");
JSONArray postCodeJsonArray = resultsJsonArray.getJSONObject(0).getJSONArray("address_components");
String postCodeString = postCodeJsonArray.getJSONObject(7).getString("long_name").toString();
Log.e("TAG", postCodeString);
Hope that helps.
reader.getJSONObject(1).getJSONArray("address_components");
Your problem is that results is a JSONArray that contains a child JSONObject composed of several children: "address_components", "formatted_address", "geometry", and "types". The result array actually contains many of these such objects, but let's focus on just the first child for now.
Look carefully at your code. With this line:
JSONArray resultArry = reader.getJSONArray("results");
You are getting the entire results. Later on, you then call the same method again:
JSONArray postCodeArray = reader.getJSONArray("address_components");
But you're asking for an "address_components" from the reader, where I do not expect you'll find anything (having already read the entire result before.) You should instead be working with the JSONArray you already got before, since it already contains the entire result.
Try something like:
JSONObject addressComponents = resultArry.getJSONObject(1).getJSONObject("address_components");
String postCode = addressComponents.getString("long_name");
Note: I don't know why you're singling out JSONObject #1 (as opposed to 0, which is the first, or any other one of them) and I also am not sure why you named the String postCode. So if I've misunderstood your intention, I apologize.
Is difficult to find the error... because all looks well. The problem maybe can exist when you make the json.put("address_components", something);
So my advice is put a breakpoint at this line
JSONArray postCodeArray = reader.getJSONArray("address_components");
o display the json in logcat
Log.d("Simple", reader.toString());
Then Paste your json in this web page to view more pretty
http://jsonviewer.stack.hu/
and check if all keys are stored well.
Solution
Need to get each array, and then get the post code value. The value 7 is used, as that is the JSONObject that has the postcode stored in the "long_name" field.
JSONObject readerJsonObject = new JSONObject(in);
readerJsonObject.getJSONArray("results");
JSONArray resultsJsonArray = readerJsonObject.getJSONArray("results");
JSONArray postCodeJsonArray = resultsJsonArray.getJSONObject(0).getJSONArray("address_components");
String postCodeString = postCodeJsonArray.getJSONObject(7).getString("long_name").toString();
Log.e("TAG", postCodeString);
Hope that helps.

How is this JSON string supposed to be parsed to get the different fields

I have this JSON string that I am recieving after I make a purchase from the playstore and I am apparently missing something in my code when I am trying to parse it.
PurchaseInfo:{"orderId":"12999763165555505758.1317333586444405",
"packageName":"com.mypkgname.myapp",
"productId":"monthly_purchase_01",
"purchaseTime":1357456489000,
"purchaseState":0,
"purchaseToken":"yrynypfkdncvhlxdbypysvwz.AO-J1OxFkndfqkClAqbbYAOApkMgTG4VX9Ef0uNP0FIs9-xGrXivkbx3FNMA2yNU12K_sbvRGFcknVBTfisI-uZawCXLGlMX4v4Zw8GFOmS0Q6PIbiITTGqn5h1QbEB4Rv84sXdUJHP3B_UQfujZN7ADi9bm_N4_iA"}
Here is the snippet of code I am using it to attempt the parsing
try {
JSONObject j1 = new JSONObject(tester1);
JSONArray mPurchInfo = j1.getJSONArray("PurchaseInfo");
int count = mPurchInfo.length();
final String[] purchInfo = new String[count];
JSONObject q1 = mPurchInfo.getJSONObject(0);
purchInfo[0] = q1.getString("orderId");
purchInfo[1] = q1.getString("packageName");
purchInfo[2] = q1.getString("productId");
purchInfo[3] = q1.getString("purchaseTime");
purchInfo[4] = q1.getString("purchaseState");
purchInfo[5] = q1.getString("purchaseToken");
orderID=purchInfo[0];
} catch (JSONException e) {
Log.e("Error","Yes");
}
I am catching the an error as I see this last log statement in my log but I am still trying to learn the parsing JSON Strings
I hope I am at least close
Ideally I would like to have Strings set to all the values in the JSON String
orderID = ??
packageName = ??
etc.
Thanks
I have this JSON string that I am recieving after I make a purchase from the playstore
If that's really what you get back, you need to contact them and tell them to fix their API; that string is not valid JSON. There are two problems with it:
A JSON document must have an object or array as the top-level item. The string as quoted is missing a { at the beginning and a } at the end.
All keys in JSON must be in double quotes. The first one, PurchaseInfo, is not.
Also, your code is doing this:
JSONArray mPurchInfo = j1.getJSONArray("PurchaseInfo");
...but if it were valid JSON, PurchaseInfo wouldn't be an array, it'd be an object.
Looking at it, if you remove the PurchaseInfo: at the beginning, it's valid. Once you've removed that, this line:
JSONObject j1 = new JSONObject(tester1);
...will give you an object from which you can query information:
String orderId = j1.getString("orderId");

android how to parse json

public void HelloWord {
for (int i = 0; i < 20; i++) {
Log.d("Great");
}
}
The code above doesn't work why?
I try to get value name
Does anybody know where is the problem?
org.json.JSONException: Value ...Content of link... at
org.json.JSON.typeMismatch at org.json.JSONArray.
I prefer to use the GSON library, as it is a fast and effective JSON parser. Once added to the project you will need to create classes to represent the data returned. You then can call a single function to create your objects for you:
gson.fromJson();
An exceptionally good article on the use of GSON can be found at http://www.javacodegeeks.com/2011/01/android-json-parsing-gson-tutorial.html - it even uses Twitter for the example.
I think that you are missing the way that JSON works. Anything in {} is an Object, while [] designates an array. So the root of the twitter feed is a JSONObject, NOT a JSONArray:
Try something more like this:
JSONObject obj = new JSONObject(mStringBuilder.toString());
JSONObject trends = obj.getJSONObject("trends");
JSONArray today = trends.getJSONArray("2012-04-10");
for (int i = 0; i < today.length(); i++) {
JSONObject tag = today.getJSONObject(i);
String name = tag.getString("name");
// do whatever with name
}
Much easier, and its clearer how it works. JSONObjects are dictionaries, with a simple mapping between keys and values - each Object ({}) can contain either more objects, or arrays ([]) which can contain either simple integers or more objects

Categories

Resources