Trying to retrieve json value from json object in Android Studio - java

I cannot retrieve the value which is in the "callingCodes" array with Android Studio. My code seems correct but I still have error messages.
Here is the json file:
[
{
"isoName": "AF",
"name": "Afghanistan",
"currencyCode": "AFN",
"currencyName": "Afghan Afghani",
"currencySymbol": "؋",
"flag": "https://s3.amazonaws.com/rld-flags/af.svg",
"callingCodes": [
"+93"
]
},
{
"isoName": "AL",
"name": "Albania",
"currencyCode": "ALL",
"currencyName": "Albanian Lek",
"currencySymbol": "Lek",
"flag": "https://s3.amazonaws.com/rld-flags/al.svg",
"callingCodes": [
"+355"
]
},
{
"isoName": "DZ",
"name": "Algeria",
"currencyCode": "DZD",
"currencyName": "Algerian Dinar",
"currencySymbol": "د.ج.‏",
"flag": "https://s3.amazonaws.com/rld-flags/dz.svg",
"callingCodes": [
"+213"
]
}
]
Here is my java android studio code:
JSONArray jsonArray = new JSONArray(response);
for(int i = 0; i < jsonArray.length(); i++){
JSONObject data = jsonArray.getJSONObject(i);
String call = (String) data.getJSONArray("callingCodes").get(0);
countryOperatorList.add(new CountryOperator(
data.getString("isoName"),
data.getString("name"),
data.getString("currencyCode"),
data.getString("currencyName"),
data.getString("currencySymbol"),
data.getString("flag"),
call
));
}
I tried to convert the key "callingCode" into String but it returns it to as ["+93"] but I only want to recover '+93'.
But when I tried the above code I got this error message:
W/System.err: org.json.JSONException: Index 0 out of range [0..0)
Which is thrown by this line of code:
String call = (String) data.getJSONArray("callingCodes").get(0);
Does anyone have a solution so that I can retrieve the value of the callingCode key.
Thank you!

I change this on your code that is work fine with I recommend for you get value using
optJSONArray or optString this used return null if key not found
my snippet code is
try {
JSONArray array = new JSONArray(response);
for(int i = 0; i < array.length(); i++){
JSONObject data = array.getJSONObject(i);
JSONArray jsr = data.optJSONArray("callingCodes");
String call=null;
if (jsr!=null&&!jsr.isNull(0)){
// Log.e("value",jsr.optString(0));
call = jsr.optString(0)
}
countryOperatorList.add(new CountryOperator(
data.getString("isoName"),
data.getString("name"),
data.getString("currencyCode"),
data.getString("currencyName"),
data.getString("currencySymbol"),
data.getString("flag"),
call
));
}
} catch (Exception e) {
e.printStackTrace();
}

is there any particular reason that you're doing the parsing yourself? Could you not use Json with an object? the example uses Gson.
so something like (example code is in Kotlin):
val data = Gson.fromJson(yourJsonString, List<YourJsonObject>)
data class YourJsonObject(
val isoName: String,
val name: String,
val name: String,
val currencyCode: String,
val currencyName: String,
val currencySymbol: String,
val flag: String,
val callingCodes: List<String>
)
Java example:
List<YourJsonObject> data = Gson.fromJson(yourJsonString, List<YourJsonObject>)
public class YourJsonObject {
private String isoName;
private String name;
private String currencyCode;
private String currencyName;
private String currencySymbol;
private String flag;
private List<String> callingCodes;
}

Your code actually works but for case if callingCodes are not empty. You must be sure that callingCodes.length > 0 to invoke array.get(0) method.
You can use array.optString(0) that will return an empty string if callingCode doesn't exist.

Related

Trouble parsing a json array inside a json array

I am having trouble parsing a simple json in java. Here is the sample json.
[
{
"politics": [
{
"type": "admin2",
"friendly_type": "country",
"name": "United States",
"code": "usa"
},
{
"type": "admin6",
"friendly_type": "county",
"name": "Gratiot",
"code": "26_057"
},
{
"type": "constituency",
"friendly_type": "constituency",
"name": "Eighth district, MI",
"code": "26_08"
},
{
"type": "admin6",
"friendly_type": "county",
"name": "Clinton",
"code": "26_037"
},
{
"type": "admin4",
"friendly_type": "state",
"name": "Michigan",
"code": "us26"
},
{
"type": "constituency",
"friendly_type": "constituency",
"name": "Fourth district, MI",
"code": "26_04"
}
],
"location": {
"latitude": 43.111976,
"longitude": -84.71275
}
}
]
Now this gives me the correct json index.
JSONParser parser = new JSONParser();
Object obj = parser.parse(output);
JSONArray array = (JSONArray)obj;
String jsonobj = array.get(0).toString();
{"politics":[{"code":"usa","name":"United States","type":"admin2","friendly_type":"country"},{"code":"26_057","name":"Gratiot","type":"admin6","friendly_type":"county"},{"code":"26_08","name":"Eighth district, MI","type":"constituency","friendly_type":"constituency"},{"code":"26_037","name":"Clinton","type":"admin6","friendly_type":"county"},{"code":"us26","name":"Michigan","type":"admin4","friendly_type":"state"},{"code":"26_04","name":"Fourth district, MI","type":"constituency","friendly_type":"constituency"}],"location":{"latitude":43.111976,"longitude":-84.71275}}
But I cant seem to get the attribute that I want from it.
JSONObject obj1 = new JSONObject(jsonobj);
String n = obj1.getString("admin4");
System.out.println(n);
All that I need from this json is the state which is Michigan. Where am I wrong?
Help would be really appreciated.
First, array.get(0) will get you the first element from the main array. This first element is a JSON object that has two properties politics and location. You seem to be interested in a value that is inside the array value of the politics property. You'll have to use this ((JSONArray)((JSONObject)array.get(0)).get("politics")) to get that array.
Second, admin4 is not a property it is actually a value of the type property. You'll have to loop through the array to find it.
Here is a complete example:
JSONParser parser = new JSONParser();
Object obj = parser.parse(output);
JSONArray array = (JSONArray)obj;
JSONArray politics = ((JSONObject)array.get(0)).get("politics"));
JSONObject obj = null;
for(int i = 0; i < politics.size(); i++){
if(((JSONObject)politics.get(i)).getString("type").equals("admin4")){
obj = ((JSONObject)politics.get(i));
}
}
if(obj != null){
// Do something with the object.
}
It seems that you're using the simple json library. I don't remember exactly if it is .get("politics") or .getJSONObject("politics"). There may be other mistakes in method names in my example.
the best solution to simplify your search and other operations on json object, is the convert json string to java object and doing your operations.
for convert json string to java object use follow code:
import org.codehaus.jackson.map.ObjectMapper;
import org.json.JSONException;
import org.json.JSONObject;
YourObject myObject;
ObjectMapper mapper = new ObjectMapper();
try{
myObject= mapper.readValue(jsonData, myObject.class);
}
catch (Exception e) {
e.printStackTrace();
}
for example define your class ass follow :
public class myObject{
private List<Politics> politics;
private Location location;
// define getters and setters
}
define Politics and Location class:
public class Politics
{
String type;
String friendly_type;
String name;
String code;
// define getters and setters
}
public class Location
{
String latitude;
String longitude;
// define getters and setters
}
It's because your are trying to get the inner element of the JSON Object.
try
JSONObject obj1 = new JSONObject(jsonobj);
JSONArray arr = (JSONArray) obj1.getObject("politics");
You will get a JSONArray object which further constitutes of JSON objects.
Now in order to get values using the key you must iterate array as given below:
for(int i=0; i<arr.size(); i++){
JSONObject obj = arr.getJSONArray(i);
System.out.println(obj.getString("type"));
}
which will now provide you with output:
admin2
admin6
constituency
admin6
admin4
constituency

Getting a Value from a JsonArray using gson

I have searched everywhere and cannot find out how to do this, I'm super stuck. I have NO experience with JSON files, so spoon feeding is appreciated along with an explanation.
I have this JSON text here for testing:
{
"id":"4566e69fc90748ee8d71d7ba5aa00d20",
"properties":
[
{
"name":"textures",
"value":"eyJ0aW1lc3RhbXAiOjE0ODI4ODAxNDMwNzYsInByb2ZpbGVJZCI6IjQ1NjZlNjlmYzkwNzQ4ZWU4ZDcxZDdiYTVhYTAwZDIwIiwicHJvZmlsZU5hbWUiOiJUaGlua29mZGVhdGgiLCJ0ZXh0dXJlcyI6eyJTS0lOIjp7InVybCI6Imh0dHA6Ly90ZXh0dXJlcy5taW5lY3JhZnQubmV0L3RleHR1cmUvMTNlODFiOWUxOWFiMWVmMTdhOTBjMGFhNGUxMDg1ZmMxM2NkNDdjZWQ1YTdhMWE0OTI4MDNiMzU2MWU0YTE1YiJ9LCJDQVBFIjp7InVybCI6Imh0dHA6Ly90ZXh0dXJlcy5taW5lY3JhZnQubmV0L3RleHR1cmUvMjJiOWM1ZWE3NjNjODZmYzVjYWVhMzNkODJiMGZhNjVhN2MyMjhmZDMyMWJhNTQ3NjZlYTk1YTNkMGI5NzkzIn19fQ==",
},
],
"name":"Thinkofdeath",
}
I currently have this:
JsonElement playerProfile = new JsonParser().parse(jsonLine);
JsonObject jsonProfile = playerProfile.getAsJsonObject();
JsonArray properties = jsonProfile.getAsJsonArray("properties");
Which returns
[
[
{
"name":"textures",
"value":"eyJ0aW1lc3RhbXAiOjE0ODI4ODAxNDMwNzYsInByb2ZpbGVJZCI6IjQ1NjZlNjlmYzkwNzQ4ZWU4ZDcxZDdiYTVhYTAwZDIwIiwicHJvZmlsZU5hbWUiOiJUaGlua29mZGVhdGgiLCJ0ZXh0dXJlcyI6eyJTS0lOIjp7InVybCI6Imh0dHA6Ly90ZXh0dXJlcy5taW5lY3JhZnQubmV0L3RleHR1cmUvMTNlODFiOWUxOWFiMWVmMTdhOTBjMGFhNGUxMDg1ZmMxM2NkNDdjZWQ1YTdhMWE0OTI4MDNiMzU2MWU0YTE1YiJ9LCJDQVBFIjp7InVybCI6Imh0dHA6Ly90ZXh0dXJlcy5taW5lY3JhZnQubmV0L3RleHR1cmUvMjJiOWM1ZWE3NjNjODZmYzVjYWVhMzNkODJiMGZhNjVhN2MyMjhmZDMyMWJhNTQ3NjZlYTk1YTNkMGI5NzkzIn19fQ==",
},
]
Of course. How do I get the "value" from this JsonArray? Note I'm using Google's API, Gson
You can get values using:
JsonObject propertiesJson = properties.get(0);
String value = propertiesJson.getString("value");
array is JsonArray object from com.google.gson library
for (int i=0; i<array.size(); i++) {
JsonObject json = array.get(i).getAsJsonObject();
String value = json.get("key").getAsString();
}

Android JSON parsing Json Array is [] Throws Null Pointer Exception while parsing, How to write in Proper way?

I have complex API that i parse and show in list view,I will be struggle to parse JSONArray.Here i will be in struggle following Json Array which is inside the posts json object "tags_name": ["Activities"],,some object it will come like "tags_name": [], this.Kindly review my question. My API and code is below. Presently i will implemented parsing code with model class. Once fix this issue i have to write list view coding please help me. May be my question formation is in silly way. please it look like means give some suggestion to frame question. Thanks in Advance.
MyAPI:
{
"status": true,
"nextpage": 0,
"count": 31,
"data": {
"postlist": [{
"posts": {},
"tags_name": ["Activities"],
"images_count": 3,
"images": [],
"post_user": [],
"is_encourage_user": true,
"encourage_feed_id": "1093"
},
{
"posts": {"id": "4647"},
"tags_name": [],
"images_count": 0,
"images": [],
"post_user": [],
"is_encourage_user": true,
"encourage_feed_id": "992"
}
]
},
"token": "wqeeqweqweqweqweqsfsdfsdf"
}
My Method for Parsing
private void parsingPostValues(String responseStatus) throws JSONException {
JSONObject responseObject = new JSONObject(responseStatus);
JSONObject datObject = responseObject.getJSONObject("data");
JSONArray postArr = new JSONArray(datObject.getString("postlist"));
for (int i = 0; i < postArr.length(); i++) {
JSONObject tempPostObject = postArr.getJSONObject(i);
JSONObject postObject = tempPostObject.getJSONObject("posts");
//setTag Array- this is the functional area i'm in bottle-neck.
try {
JSONArray tagNameArr = tempPostObject.getJSONArray("tags_name");
//ArrayList<Bean> tagListdata = new ArrayList<Bean>(tagNameArr.length());
if (tagNameArr.length()>0) {
for (int tagInfo = 0; tagInfo < tagNameArr.length(); tagInfo++) {
// listdata.add(tagNameArr.get(i).toString());
String tagme = "";
//Bean tagBean = new Bean();
//tagBean.setTagsArray((tagme.isEmpty() ? tagNameArr.get(tagInfo).toString() : "null")); //tagBean.setTagsArray(tagNameArr.get(tagInfo).toString());
//tagListdata.add(tagBean);
//beanAccess.setTagsArray(tagNameArr.get(tagInfo));
System.out.println("Tags Array:"+tagInfo+":"+tagNameArr.get(tagInfo));
}
//beanAccess.setTagsArray(tagListdata);
}
} catch (Exception e) {
e.printStackTrace();
}
}
replace this
JSONArray postArr = new JSONArray(datObject.getString("postlist"));
To
JSONArray postArr = datObject.getJSONArray("postlist");
Replace
String imgCount = tempPostObject.getString("images_count");
String is_encourage_user = tempPostObject.getString("is_encourage_user");
To
String imgCount = postObject.getString("images_count");
String is_encourage_user = postObject.getString("is_encourage_user");
It will work for you.

How to Parse this json object nested in json array

I am using this code
private void parseData(JSONArray array){
Log.d(TAG, "Parsing array");
for(int i = 0; i<array.length(); i++) {
bookItems bookItem = new bookItems();
JSONObject jsonObject = null;
try {
jsonObject = array.getJSONObject(i);
JSONObject bookChapter = jsonObject.getJSONObject("chapter");
bookItem.setbook_subtitle(bookChapter.getString("subtitle"));
JSONObject chapVerses = jsonObject.getJSONObject("verses");
JSONArray verseReaders = chapVerses.getJSONArray("readers");
JSONObject readersNum = verseReaders.getJSONObject("number");
verseReadNum = readersNum;
} catch (JSONException w) {
w.printStackTrace();
}
mbookItemsList.add(bookItem);
}
}
to parse this json.
[
{
"chapter": {
"subtitle": "Something happened in this in this chapter"
},
"verses": {
"about": [
{
"In this verse, a lot of things happened yes a lot!"
}
],
"readers": [
{
"read": false,
"number": "No body has read this verse yet"
}
],
}
},
...]
I am getting the "subtitle" correctly but I am having didfficulty getting "number".
From line JSONObject readersNum = verseReaders.getJSONObject("number"); Android studio is complaining that getJSONOBJECT (int) in JSONArray cannnot be applied to (java.lang.String)
Please, how do I properly parse this?
verseReaders is a JSONArray, so you need to iterate over (or take the first) JSONObject and then get the string from that object.
String readersNum = verseReaders.getJSONObject(0).getString("number");
You have to use nested loops. Just add one more for for "readers".

Android - How to parse JSONObject and JSONArrays from api.rottentomatoes

so, there's this JSON code. Im trying to get the "abridged_cast".
but its complicated.
its JSONObject
inside JSONArray onside jSONObject Inside JsonArray....
{
"total": 591,
"movies": [
{
"title": "Jack and Jill",
"year": 2011,
"runtime": "",
"release_dates": {
"theater": "2011-11-11"
},
"ratings": {
"critics_score": -1,
"audience_score": 90
},
"synopsis": "",
"posters": {
"thumbnail": "",
"profile": "",
"detailed": "",
"original": ""
},
"abridged_cast": [
{
"name": "Al Pacino",
"characters": []
},
{
"name": "Adam Sandler",
"characters": []
},
{
"name": "Katie Holmes",
"characters": []
}
],
"links": {
"self": "",
"alternate": ""
}
}
],
"links": {
"self": "",
"next": ""
},
"link_template": ""
}
this is my code for getting "title" and "year"
if (response != null) {
try {
// convert the String response to a JSON object,
// because JSON is the response format Rotten Tomatoes uses
JSONObject jsonResponse = new JSONObject(response);
// fetch the array of movies in the response
JSONArray movies = jsonResponse.getJSONArray("movies");
// add each movie's title to an array
movieTitles = new String[movies.length()];
for (int i = 0; i < movies.length(); i++) {
JSONObject movie = movies.getJSONObject(i);
movieTitles[i] = movie.getString("title");
}
hope someone would help me because i cant figure out how to get the abridged_cast"
movies contains an array of "movie" objects. Each one of those objects contains a field abridged_cast that is an array of (let's call them "cast member") objects.
If you're not going to map to a POJO and instead are going through the JSON, you simply need to get that array in your loop after getting movie, and get each "cast member" object from that array in the same manner using another loop.
...
JSONArray cast = movie.getJSONArray("abridged_cast");
for (int j = 0; j < cast.length(); j++) {
JSONObject castMember = cast.getJSONObject(j);
...
}
Edit from comments: Your original question involved how to extract the information from the JSON you have; the above code explains that. It now seems like you're asking a more fundamental programming question around how to use it.
If you're going to use the included org.json classes that come with Android, you now know how to access the information in the returned JSON object. And you could write methods around the parsed JSONObject to access the data as-is using the objects and methods from the json.org package. For example, you could write a "getMovie()" method that took the name of the movie as a string and searched that "movies" array for the right one and returned it as a JSONObject.
Normally you would create classes in Java that encapsulate the data returned in that JSON and use data structures that lend themselves to your access patterns (For example, a Map that conatained all the movies using their names as keys). Using the org.json classes you'll have to instantiate those objects and populate them manually as you parse the JSON like you're doing in your question. If you used either the Gson or Jackson JSON parsing libraries they are capable of taking the JSON you have and mapping all the data to the classes your create and returning them in a single call.
try {
String Movie = null;
String abridged = null;
JSONArray jsonResponse = new JSONArray(response);
for (int i = 0; i< jsonResponse.length(); i++) {
Movie = jsonResponse.getJSONObject(i).getString("movies").toString();
System.out.println("movies="+Movie);
abridged = jsonResponse.getJSONObject(i).getString("abridged_cast").toString();
}
JSONArray jArray = new JSONArray(Movie);
for (int i = 0; i< jArray.length(); i++) {
String title = jArray.getJSONObject(i).getString("title").toString();
System.out.println("title="+title);
}
JSONArray jabridgeArray = new JSONArray(abridged);
for (int i = 0; i< jabridgeArray.length(); i++) {
String title = jabridgeArray.getJSONObject(i).getString("name").toString();
System.out.println("title="+title);
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

Categories

Resources