How to Parse this json object nested in json array - java

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".

Related

Trying to retrieve json value from json object in Android Studio

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.

Class cast exception [JSONArray cannot be cast to org.json.simple.JSONObject]

I have a json file like this
[ {
"id":"serve-coffee",
"tags":[ {
"name": "#tag1", "line": 1
}
],
"description":"Coffee should not be served\n",
"name":"Serve coffee",
"keyword":"Feature",
"line":2,
"elements":[ {
"id": "serve-coffee;buy-last-coffee", "tags":[ {
"name": "#tag2", "line": 6
}
],
"description":"",
"name":"Buy last coffee",
"keyword":"Scenario",
"line":7,
"steps":[ {
"name": "there are 1 coffees left in the machine", "keyword": "Given ", "line": 8
}
,
{
"name": "I have deposited 1$", "keyword": "And ", "line": 9
}
],
"type":"scenario"
}
],
"uri":"src\/test\/resources\/traffic-remove-locations.feature"
}
]
Iam trying to convert the above json file to JSONObject.But am getting class cast exception "java.lang.ClassCastException: org.json.simple.JSONArray cannot be cast to org.json.simple.JSONObject"
code
public static JSONObject convertFileToJSON(String fileName) throws ParseException {
// Read from File to String
JSONParser parser = new JSONParser();
JSONObject jsonObject = null;
try {
Object object = parser.parse(new FileReader(fileName));
jsonObject = (JSONObject) object; // Getting classCast Exception here.
} catch (FileNotFoundException e) {
} catch (IOException ioe) {
}
return jsonObject;
}
but when i changed the line jsonObject = (JSONObject) object; to JSONArray jsonArray = (JSONObject)object the exception disappears.
But if am casting to JSONArray then how can i get the values like id,tags and description from JSONArray.
please provide a suggestion guys
Your JSON file represents an array with one object in it. So if that were a Java data structure, you're effectively doing this:
int[] arr = {5};
int i = (int)arr;
This obviously doesn't work because you can't cast an array to a singular object. What you actually want to do it pull out the first element of the array. To continue the Java example, you want to do
int[] arr = {5};
int i = (int)arr[0];
With the JSON stuff, your parser.parse() call returns a JSONArray, not a JSONObject. So you'll need to do something like this:
public static JSONObject convertFileToJSON(String fileName) throws ParseException {
JSONParser parser = new JSONParser();
JSONObject jsonObject = null;
try {
JSONArray array = (JSONArray) parser.parse(new FileReader(fileName));
jsonObject = array.getJsonObject(0);
} catch (FileNotFoundException e) {
} catch (IOException ioe) {
}
return jsonObject;
}
Try casting to JsonArray and then cast access the objects one by one with help of the index from the JSON array.
Object object = parser.parse(new FileReader(fileName));
JsonArray jsonArr = (JsonArray) object; // Getting c
jsonObject jsonObj = jsonArr.get(0); //use index to access like a list
I was also facing the same issue. I did the below changes to make it work.
Below is my sample JSON.
{
"routes": [{
"startTime": 1520319414,
"routeInfo": [{
"routePart": 0,
"transType": "WALK",
"transDetails": {
"startLoc": {
"lat": 28.6434862,
"lon": 77.22542659999999
}
}
}, {
"routePart": 1,
"transType": "BUS",
"transDetails": {
"routeNumber": "307-U",
"interStopDetails": [{
"seq": 1,
"name": "test1",
"loc": {
"lat": 28.64302,
"lon": 77.2260367
},
"eta": 1520319600
}
]
}
}
],
"totalTime": 5742
}
]
}
Solution to Parse:
JSONObject obj = (JSONObject) jsonParser.parse(new FileReader(FilepathDummy));
JSONArray jsonRoutes= (JSONArray) obj.get("routes"); //Gives Main JSoN
JSONObject routeJsonObject = (JSONObject) jsonRoutes.get(0); // Route Array into JSON
JSONArray routeInfoArray = (JSONArray) routeJsonObject.get("routeInfo"); // RouteInfo Array
Hope this solve your problem.

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.

Java: How to decode JSON within Android? What am I doing wrong?

I've got an Android app in which I get some JSON from an API, which I now need to decode. I'm pretty far, but I'm failing at getting the contents. The JSON I'm receiving looks like this:
{ "messages": [
{
"created": "1391783287",
"id": 1,
"is_supporter": false,
"text": "Behold! This is a message?"
},
{
"created": "1391783287",
"id": 3,
"is_supporter": true,
"text": "Behave! This is an answer!"
}
]}
And I've got this code:
#Override
protected void onPostExecute(String result) {
try{
JSONArray jArray = new JSONArray(result);
And on the last line of the code above I get an error saying Error: org.json.JSONException: Value {"messages":[{"id":1,"created":"1391788514","text":"How do I pay to an IBAN?","is_supporter":false},{"id":3,"created":"1391788514","text":"What is a payment pool?","is_supporter":false}]} of type org.json.JSONObject cannot be converted to JSONArray
Does anybody have any idea whats wrong here or how I can solve this?
Your String is a JSON object containing a JSON array, try this :
JSONObject myJSON = new JSONObject(result);
JSONArray jArray = myJSON.getJSONArray("messages");
then iterate through your JSONArray ...
int size = jArray.length();
for (int i=0 ; i<size ; i++){
JSONObject itemInArray = jArray.get(i);
// get values inside the object, for example :
String text = itemInArray.getString("text");
}
You can use old http://www.json.org lib in your Java :
First read your json file content into String;
Then parse it into JSONObject, If there is array, then get the array;
JSONObject myJson = new JSONObject(myJsonString);
// get the JsonArray
JSONArray jArray = jobj.getJSONArray("messages");
//Loop through the array to get the JSONObjects
for(int i=0;i<jArray.length();i++) {
// use myJson as needed, for example
int id = jArray.getJsonobject(i).getString("id");
// etc
}
you are JSONArray is in inside the JSONObject
Do like this to get the data
#Override
protected void onPostExecute(String result) {
try {
JSONObject jobj = new JSONObject(result);
JSONArray jArray = jobj.getJSONArray("messages");
for(int i=0;i<jArray.length();i++) {
String created=jArray.getJsonobject(i).getString("created");
}
}

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