JAVA parsing inner JSON - android

I am trying to take "key" value in a JSON file. I tried many solutions but I couldn't handle this ,it constantly gives me "at videos of type org.json.JSONObject cannot be converted to JSONArray" error. How can I solve this. Thank you.
My JSON data;
{ videos: {
results:[
{
id: "56c4ccbfc3a3680d52000610",
iso_639_1: "en",
iso_3166_1: "US",
key: "nIGtF3J5kn8",
}
]
}
}
My code;
JSONArray Movie_List = Search_Results.getJSONArray("videos");
for (int i = 0; i < Movie_List.length(); i++)
{
JSONObject movie = (JSONObject) Movie_List.get(i);
JSONArray Movie_List1 = movie.getJSONArray("results");
for (int j = 0; j < Movie_List1.length(); j++)
{
JSONObject movie2 = (JSONObject) Movie_List1.get(j);
key = movie2.getString("key");
}
}
The error;

Try some like this.. Your mistake come because you try to parse videos to JSONArray but it is JSONObject...
JSONObject videos = Search_Results.getJSONObject("videos");
JSONArray result= videos.getJSONArray("results");
for (int i = 0; i < result.length(); i++)
{
JSONObject movie = result.getJSONObject(i);
String movieId = movie.getString("id");
//and other values .. same way
}

Related

how to get json which has multiple values in a string in android

I have a json which has multiple values separated by commas which is in the
form of array.I want to get skills and platforms string separately.Can you please help me?
I want to show skills string and platforms string in text.
Please help me.
The format is:
{
"data": [
{
"skills": "ANDROID SDK, ANIMATION, ANGULARJS,",
"platforms": "IOS Application, Social Networking, Online shopping Sites, Web Application"
}
],
"status": 100
}
Try this one
try {
JSONObject ob = new JSONObject(response);
int status = ob.getInt("status");
if (status == 100) {
JSONArray ja = ob.getJSONArray("data");
for (int i = 0; i < ja.length(); i++) {
values = new HashMap<>();
JSONObject vj = ja.getJSONObject(i);
String skills = vj.getString("skills "));
String platforms=vj.getString("platforms"));
data.add(values);
}
split these 2 strings using 'split()'
List<String> skillsArray = Arrays.asList(skills.split(","));
List<String> platformsArray= Arrays.asList(platforms.split(","));
String in = "your json";
JSONObject jsonObj = new JSONObject(in);
// Getting JSON Array node
JSONArray jsonarray = jsonObj.getJSONArray("data");
for (int i = 0; i < jsonarray.length(); i++) {
JSONObject jsonobject = jsonarray.getJSONObject(i);
String skills = jsonobject.getString("skills");
String platforms = jsonobject.getString("platforms");
}
Try this
JSONObject jsonObject = new JSONObject("Your json response");
JSONArray jsonArray = jsonObject.getJSONArray("data");
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonobject = jsonArray.getJSONObject(i);
String skill = jsonobject.getString("skills");
String platforms = jsonobject.getString("platforms");
String[] skillsArray = skill.split(Pattern.quote(","));
String[] platformsArray = platforms.split(Pattern.quote(","));
for (int j=0; j<skillsArray.length; j++)
{
Log.i("Skill Value ", "=" + skillsArray[j]);
}
for (int j=0; j<platformsArray.length; j++)
{
Log.i("platforms Value ", "=" + platformsArray[j]);
}
}
Output
First of all convert your output string into json. Note that output string is the string which contains your results of json format that you have posted above.following is the code on how to do that:
JSONObject myJsonResponse = new JSONObject(yourString);
The next one is Array. That is how you will get it and will iterate over it.
JSONArray jsonarray = jsonObj.getJSONArray("data");
for (int i = 0; i < jsonarray.length(); i++) {
JSONObject innerJsonObject= jsonarray.getJSONObject(i);
String skills = innerJsonObject.getString("skills");
String platforms = innerJsonObject.getString("platforms");
}
Now you have gotten your required fields and you can now perform any String functions over the String skills and platforms.
Happy coding. .
The best way is creating a model class such :
public class MyModel{
Properties [] data;
class Properties{
public String skills;
public String platforms;
}
}
then you can parse your string to model with Gson library like this :
MyModel myModel = new Gson().fromJson(yourString, MyModel.class)
so all data is in myModel object and you can access to skills with
myModel.data[0].skills
to add Gson library to your project add below to your app gradle file :
compile 'com.google.code.gson:gson:2.8.1'
You may try this,
JSONObject jsonObject = null;
try {
jsonObject = new JSONObject("JSON_STRING");
JSONArray jsonArray = jsonObject.getJSONArray("data");
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonobject = jsonArray.getJSONObject(i);
String skills = jsonobject.getString("skills");
String[] seperateData = skills.split(Pattern.quote(","));
for (int j = 0; j < seperateData.length; j++) {
Log.e("Your Skill Value-> ", seperateData[j]);
}
String platforms = jsonobject.getString("platforms");
seperateData = platforms.split(Pattern.quote(","));
for (int j = 0; j < seperateData.length; j++) {
Log.e("Your Platform Value-> ", seperateData[j]);
}
}
} catch (JSONException e) {
e.printStackTrace();
}
class Data{
public String skills;
public String platforms;
}
Gson gson = new Gson();
JSONArray dataArray = response.getJSONArray("data");
List<Data> dataList= gson.fromJson(dataArray toString(), new TypeToken<List<Data>>() {
}.getType());
Try this.. It will make parsing easier.
implementation 'com.google.code.gson:gson:2.8.0'
First Parse your JSON:
JSONObject jsonObj = new JSONObject(in);
JSONArray jsonarray = jsonObj.getJSONArray("data");
for (int i = 0; i < jsonarray.length(); i++) {
JSONObject jsonobject = jsonarray.getJSONObject(i);
String skills = jsonobject.getString("skills");
String platforms = jsonobject.getString("platforms");
}
Then Split your string values:
String skills = "ANDROID SDK, ANIMATION, ANGULARJS";
String[] separated = CurrentString.split(",");
separated[0]; // this will contain "ANDROID SDK"
separated[1]; // this will contain " ANIMATION"
separated[2]; // this will contain " ANGULARJS"
You have to remove the space to the second String:
separated[1] = separated[1].trim();
Try this you will be getting all values of sapereted with commas
jsonString = getting string from server side
String[] separated = jsonString.split(",");
StringBuilder s = new StringBuilder(10000);
for (int i = 0; i < separated.length; i++) {
if (i == separated.length - 1) {
s.append(separated[i].trim() + "");
} else {
s.append(separated[i].trim() + ",\n");
}
}
//tvDisplayAddress.setText(s);
Log.e("VALUES: ",s+"");

getJSONArray inside another json array

I have the following JSON struncture:
{
"schedule":{
"day":[
{
"id":"Monday",
"items":[
{
},
{
}
]
},
{
"id":"Tuesday",
"items":[
{
},
{
}
]
}
]
}
}
And what I basically want to do is reach the items array inside the day array which is inside the schedule object.
But whenever I try to get the second JSON array, I get getJSONArray
(int) in JSONArray cannot be applied to (java.lang.String).
JSONObject baseJsonResponse = new JSONObject(dayJSON);
JSONArray dayArray = baseJsonResponse.getJSONObject("schedule").getJSONArray("day").getJSONArray("items");
You should use Two for loop respect to JSONArray.
JSONObject obj = new JSONObject(success);
JSONObject JOBJ_Schedule = obj.getJSONObject("schedule");
JSONArray schedule_Array = JOBJ_Schedule.getJSONArray("day");
for (int i = 0; i < schedule_Array.length(); i++)
{
JSONObject jOBJ = schedule_Array.getJSONObject(i);
JSONArray jArray = jOBJ.getJSONArray("items");
for (int j = 0; j < jArray.length(); j++)
{
JSONObject jOBJNEW = jArray.getJSONObject(j);
}
}
Looks like day is a list of objects. So basically, you'd have to do something like getJSONArray("day").get(0).getJSONArray("items").
you can try this
try {
JSONObject baseJsonResponse = new JSONObject("dayJSON");
JSONObject schedule= baseJsonResponse.getJSONObject("schedule");
JSONArray day=schedule.optJSONArray("day");
for (int i=0; i<day.length(); i++) {
JSONObject data = day.getJSONObject(i);
String id = data.getString("id");
JSONArray items = data.getJSONArray("items");
for (int j = 0; j < items.length(); j++) {
JSONObject data2 = day.getJSONObject(i);
String str = data2.getString("YOurkey");
Log.e("categories", str);
}
}
} catch (JSONException e) {
e.printStackTrace();
}
According to the JSON you provided, baseJsonResponse.getJSONObject("schedule").getJSONArray("day") will return you a JSONArray instead of JSONObject.
There is a "item" JSONArray inside each "day" JSONObject. < May be this is the reason.
You can try
for(int i = 0 ; i < baseJsonResponse.getJSONObject("schedule").getJSONArray("day").length() ; i++){
JSONArray itemArray = baseJsonResponse.getJSONObject("schedule").getJSONArray("day")
.getJSONObject(i).getJSONArray("items");
}

Android JSON getJSONObject not working, incorrect parsing

I cannot figure out why my parsing is not working, this is my JSON:
{
"fileVersion":"1.0",
"graves":[
{
"ID_grave":"1",
"ID_line":"1",
"sequence":"1",
"persons":[
{
"ID_person":"1",
"name":"Janez",
"surname":"Novak",
"dateBirth":"1956-08-11",
"dateDeath":"2014-02-12",
"important":"0",
"imp_desc":""
}
]
},
{
"ID_grave":"2",
"ID_line":"1",
"sequence":"2",
"persons":[
{
"ID_person":"2",
"name":"Mojca",
"surname":"Novak",
"dateBirth":"1953-02-13",
"dateDeath":"2012-04-08",
"important":"0",
"imp_desc":""
}
]
}
]
}
This code is working, when I want to get the first JSONObject:
String jsonData = convertStreamToString(in);
JSONObject json = new JSONObject(jsonData);
JSONArray name = json.getJSONArray("graves");
for (int i = 0; i < name.length(); i++) {
JSONObject grave = name.getJSONObject(i);
lineArrayList.add(grave.getString("ID_line"));
graveArrayList.add(grave.getString("ID_grave"));
}
But I would like to get the "persons" array in "graves" object. This should work but it's not, I am getting only the first persons array, where the name is Janez and not the second array where the name is Mojca:
String jsonData = convertStreamToString(in);
JSONObject json = new JSONObject(jsonData);
JSONArray name = json.getJSONArray("graves");
for (int i = 0; i < name.length(); i++) {
JSONObject grave = name.getJSONObject(i);
JSONArray persons = grave.getJSONArray("persons");
for (int k = 0; k < persons.length(); k++) {
//The problem was because of the index i, you have to change to k and it will work
JSONObject grave = persons.getJSONObject(i);
nameArrayList.add(grave.getString("name"));
surnameArrayList.add(grave.getString("surname"));
}
}
graves is a JSONArray and persons is a JSONArray into graves
for (int i = 0; i < name.length(); i++) {
JSONObject grave = name.getJSONObject(i);
JSONArray persons = grave.optJSONArray("persons");
if (persons != null) {
for (int j = 0; j < persons.length(); j++) {
}
}
}
Do your parsing as follows ,
String jsonData = convertStreamToString(in);
JSONObject json = new JSONObject(jsonData);
JSONArray name = json.getJSONArray("graves");
for (int i = 0; i < name.length(); i++) {
JSONObject grave = name.getJSONObject(i);
JSONArray persons = grave.getJSONArray("persons");
for (int k = 0; k < persons.length(); k++) {
JSONObject grave = persons.getJSONObject(i);
nameArrayList.add(grave.getString("name"));
surnameArrayList.add(grave.getString("surname"));
}
}
Try This:
for (int i = 0; i < name.length(); i++) {
JSONObject grave = name.getJSONObject(i);
JSONArray persons = grave.optJSONArray("persons");
if (persons != null) {
for (int j = 0; j < persons.length(); j++) {
JSONObject grave= persons.getJSONObject(i);
lineArrayList.add(grave.getString("ID_line"));
//so on..
}
}
Ok only today I discovered that I am getting the data only from the first persons array and from the second where for example is a person with a name Mojca..I tried all the three given solutions but nothing works..

How to convert the json array to string array in android?

I am converting an json array to string array thats doesn't exist any tag. I tried with all tricks but not succeeded.
json array:-
"validValues":["01_Abacus","02_AlarmClock","03_Basketball","04_Beaker","55_Watch"]
Code for convert the json array to string values
if (jsonComponentObj.has(TAG_VALID_VALUES)) {
String value = jsonComponentObj.getString(TAG_VALID_VALUES);
Logs.e("value " + value);
if (!value.equals("null")) {
JSONArray jsonArray = jsonComponentObj
.getJSONArray(TAG_VALID_VALUES);
if (jsonArray != null) {
ArrayList<String> stringArray = new ArrayList<String>();
for (int j = 0; j < jsonArray.length(); j++) {
try {
JSONObject jsonObject = jsonArray
.getJSONObject(j);
stringArray.add(jsonObject.toString());
} catch (JSONException e) {
Logs.e("Exception: "+e.toString());
e.printStackTrace();
}
}
}
}
}
Exception:
org.json.JSONException: Value 01_Abacus at 0 of type java.lang.String cannot be converted to JSONObject
If anyone have idea. Please reply. Thanks in advance..
Because validValues JSONArray contain only Strings instead of JSONObject.so get all values from JSONArray as:
for (int j = 0; j < jsonArray.length(); j++) {
String str_value = jsonArray.optString(j);
stringArray.add(str_value);
}
Your json array contains Strings not json object.Therefore to get Strings from json array directly use getString(),So
Change
JSONObject jsonObject = jsonArray.getJSONObject(j);
stringArray.add(jsonObject.toString());
to
stringArray.add(jsonArray.getString(j));
or
stringArray.add(jsonArray.optString(j));
You should use optString(int) to coerce a string value from array. Using getString(int) would cause problems if ever the values in the array were not strings.
for (int j = 0; j < jsonArray.length(); j++) {
String value = jsonArray.optString(j);
stringArray.add(value);
}
If you want to give a default value, use optString(int, String).
try JSONObject jsonObject = jsonArray.getString(j);
instead of JSONObject jsonObject = jsonArray.getJSONObject(j);

How to parse Json data from URL?which contains number of arrays

i am having a issue of parsing JSON data i followed this link..
over there it has parsing data images description..
and i also refereed this in stack over flow a guy who is having same issue but no correct answer..
How to Parse JSONarray inside JSONarray in android? and
How to display Image from URL?
we can say just extention of the above questions..
its not a duplicate that guy is also same problem no answer..
i have a data like below
{
"request": "ok",
"query": {
"result": [
{
"site": [
{
"latest": [
{
"id": "2eaQy8Ow",
"data": "1/1/2014"
}
]
}
],
"flag": [
"http://www.simplydecoded.com/wp-content/uploads/2013/02/Telangana2.jpg"
]
}
]
}
}
i am using below code for parsing
JSONArray json_query_flag = c.getJSONArray("flag");
JSONArray json_query_site=c.getJSONArray("site");
System.out.println("looping json_query_site");
for (int j = 0; j < c.length(); j++) {
System.out.println("looping json_query_site[" + j +"]" + "json_query_site.length() -->" + json_query_site.length());
if (j <json_query_site.length()) {
HashMap<String, String> map1 = new HashMap<String, String>();
JSONObject sd = json_query_site.getJSONObject(j);
// get latestoffers
JSONArray json_latest = sd.getJSONArray("latest");
System.out.println(json_latest.toString());
for (int k = 0; k < json_latest.length(); k++) {
HashMap<String, String> map2 = new HashMap<String, String>();
JSONObject e = json_latest.getJSONObject(k);
My problem is that i am not getting the latest and flag..
may be parsing problem..
Hellow man thanks for understanding the problem please follow this post for the till your site and latest..
it solved I am getting text.. but problem with images I think you have flag..
for that you need to change your Listviewadapter.java file. so that images will appear
change this like
String strflag = resultp.get(Mainactivity.IMAGES);
if(strflag != null)
imageLoader.DisplayImage(strflag, flag);
else
imageLoader.DisplayImage("http://www.butterentals.com/graphics/no_image.jpg", flag);
so that I will be done.
TRy this..
JSONObject JObj = new JSONObject(response);
JSONObject query = JObj.getJSONObject("query");
JSONArray result = query.getJSONArray("result");
for (int i = 0; i < result.length(); i++) {
JSONObject jobj = result.getJSONObject(i);
JSONArray site = jobj.getJSONArray("site");
for (int j = 0; j < site.length(); j++) {
JSONObject sitobj = site.getJSONObject(j);
JSONArray latest = sitobj.getJSONArray("latest");
for (int k = 0; k < latest.length(); k++) {
JSONObject lateobj = latest.getJSONObject(k);
System.out.println("id : "+lateobj.getString("id"));
}
}
JSONArray flag = jobj.getJSONArray("flag");
for (int l = 0; l < flag.length(); l++) {
System.out.println("urls : "+flag.getString(l));
}
}

Categories

Resources