Not able to extract array elements from JSON in android - android

I have been trying to extract array elements from my JSON, but unable to, so far.
I have the following JSON:
{
"Sample JSON": [{
"Title": "Title1",
"Audit": [{
"auditId": "01",
"type": "sampleType",
"auditText": "sampleText",
"answer": ["Ans1", "Ans2"]
},
{
"auditId": "02",
"type": "sampleType2",
"auditText": "sampleText2",
"answer": ["Ans1", "Ans2", "Ans3", "Ans4"]
}
]
},
{
"Title": "Title2",
"Audit": [{
"auditId": "03",
"type": "sampleType3",
"auditText": "sampleText3",
"answer": ["Ans1", "Ans2"]
},
{
"auditId": "04",
"type": "sampleType4",
"auditText": "sampleText4",
"answer": ["Ans1", "Ans2", "Ans3", "Ans4"]
}
]
}
]
}
I want to extract the array elements of the array 'answer'.
I get exception in the line indicated in comment in the method below:
public void getAudit(String myJSON) {
auditList = new ArrayList<AuditList>();
String title;
String auditId;
String type;
String auditText;
ArrayList<String> answer = new ArrayList<>();
try {
JSONObject jsonObj = new JSONObject(myJSON);
JSONArray jssArray = jsonObj.getJSONArray("Sample JSON");
int jsonArrLength = jssArray.length();
for (int i = 0; i < jsonArrLength; i++) {
JSONObject jsonChildObj = jssArray.getJSONObject(i);
title = jsonChildObj.getString("Title");
JSONArray jssArray1 = jsonChildObj.getJSONArray("Audit");
for (int i1 = 0; i1 < jssArray1.length(); i1++) {
JSONObject jsonChildObj1 = jssArray1.getJSONObject(i1);
type = jsonChildObj1.optString("type");
auditText = jsonChildObj1.optString("auditText");
auditId = jsonChildObj1.optString("auditId");
JSONArray jssArray2 = jsonChildObj1.getJSONArray("answer");
//Getting exception in above line
for (int j=0; j<jssArray2.length(); j++)
{
answer.add(jssArray2.get(j).toString()) ;
}
AuditList aList = new AuditList();
aList.setQuesId(auditId);
aList.setQuesText(auditText);
aList.setQuesTypw(auditType);
aList.setAnswer(answer);
aList.setCategoryName(title);
auditList.add(aList);
}
}
.
.
.
.
.
}
I found the exception occurring in the line indicated above using the debugger.
Couldn't find a way to extract array elements of the array 'answer'.
Please help.

if(!jsonChildObj1.get("answer").toString().equals("")){
JSONArray jssArray2 = jsonChildObj1.getJSONArray("answer");
for (int j=0; j<jssArray2.length(); j++)
{
answer.add(jssArray2.get(j).toString()) ;
}
}
The exception that occurred to you because of Empty Data (""). To Prevent this validate it and getJSONArray(). refer

The way I do this kind of stuff is by going to this link and then paste my json there and get my class. After that, you can go and add Gson to your gradle by adding this line to your build.gradle:
compile 'com.google.code.gson:gson:2.6.2'
Then just create an instance of the created class that you just created and convert json into your target class:
NewClass classObject = new Gson().fromJson(YOUR_JSON, NewClass.class);

Related

Remove The Json Value From Json

I want to remove json value from below json file .
This is my json object :
{
"Approximation": {
"name": "Approximation",
"description": [
"Approximation",
"Approximation",
"Approximation"
],
"video": [
"evideo/package1/maths/Approximation/349188_f2ba28819a74355a456ef91d95451b71/349188_f2ba28819a74355a456ef91d95451b71/349188.mpd",
"evideo/package3/maths/approxomation/396183_Approximation/396183_fcedf516e0f5c935d561d486058fa6e0/396183.mpd",
"evideo/package2/maths/approxomation/387010_01approximation/387010_949440b1082fea19faa7dcb4aebf0b43/387010.mpd"
]
}
}
and this is what I'm trying
Code :
for (int i = 0; i < jsonArr.length(); i++) {
JSONObject jsonObj = jsonArr.getJSONObject(i);
jsonArr.remove(i);
children = new ArrayList<ChildrenEvent>();
et = new Events(jsonObj.optString("name"));
ct = new ChildrenEvent(jsonObj.optString("description"));
langs.add(et);
children.add(ct);
}
I am not sure what you are trying to achieve here. You don't need to remove the key "Approximation" to get the data.
This is how you parse this JSON.
{
"Approximation": {
"name": "Approximation",
"description": ["Approximation", "Approximation", "Approximation"],
"video": ["evideo/package1/maths/Approximation/349188_f2ba28819a74355a456ef91d95451b71/349188_f2ba28819a74355a456ef91d95451b71/349188.mpd", "evideo/package3/maths/approxomation/396183_Approximation/396183_fcedf516e0f5c935d561d486058fa6e0/396183.mpd", "evideo/package2/maths/approxomation/387010_01approximation/387010_949440b1082fea19faa7dcb4aebf0b43/387010.mpd"]
}
}
Code,
JSONObject mainObj = new JSONObject(json_string);
JSONObject appproxObj = mainObj.getJSONObject("Approximation");
// Parse name
String name = appproxObj.getString("name");
et = new Events(name);
langs.add(et);
// Parse descriptions
JSONArray descriptions = appproxObj.getJSONArray("description");
children = new ArrayList<ChildrenEvent>();
for (int i = 0; i < descriptions.length(); i++ ) {
String description = descriptions.getString(i);
ct = new ChildrenEvent(description);
children.add(ct);
}
Still if you need the JSON without key "Approximation", the variable appproxObj has the JSON without the key.
There is a method in JsonObject, that is remove(). It will help you to remove any key from jsonObject;
Use this:-
jsonObject.remove("key");

How to get all the data from a complicated json file in android?

I'm currently making a bible verse app for android, and the problem I am having might be common, but I find it difficult to implement since I'm a beginner.
How will I get each information in a string from the json data sampled below ?
{
"book": "1 John",
"chapters": [{
"chapter": "1",
"verses": [{
"1": "That which was from the beginning, which we have heard, which we have seen with our eyes, which we have looked upon, and our hands have handled, of the Word of life;"
}, {
"2": "(For the life was manifested, and we have seen it, and bear witness, and shew unto you that eternal life, which was with the Father, and was manifested unto us;)"
}]
}]
If I were to get each data so that I can use it as a string or a list, should I use a code like the following ? How can I change the code so that it can get the data from the json ? I would love to hear from you!
JSONObject obj = new JSONObject(script);
JSONArray chapters = obj.getJSONArray("chapters");
ArrayList < HashMap < String, String >> formList = new ArrayList < HashMap < String, String >> ();
HashMap < String, String > m_li;
for (int i = 0; i < chapters.length(); i++) {
JSONObject jo_inside = chapters.getJSONObject(i);
String formula_value = jo_inside.getString("chapters");
String url_value = jo_inside.getString("verse");
}
Better representation of data would be like this.
{
"book": "1 John",
"chapters": [
{
"chapter": "1",
"verses": [
{
"1": "That which was from the beginning, which we have heard, which we have seen with our eyes, which we have looked upon, and our hands have handled, of the Word of life;"
},
{
"2": "(For the life was manifested, and we have seen it, and bear witness, and shew unto you that eternal life, which was with the Father, and was manifested unto us);"
}
]
}
]
}
As you can see we have two level of list which are represented by [ ] in JSON. I have also removed unnecessary complex JSON object.
JSONObject obj = new JSONObject(script);
JSONArray chaptersList = obj.getJSONArray("chapters");
ArrayList<HashMap<String, String>> chapterHash = new ArrayList<HashMap<String, String>>();
for (int i = 0; i < chaptersList.length(); i++) {
JSONObject chapter = chaptersList.getJSONObject(i);
String chapterId = chapter.getString("chapter");
chapterHash.add(new HashMap<String, String>());
JSONArray versesList = chapter.getJSONArray("verses");
for(int j=0;j < versesList.length();j++){
JSONObject verse = versesList.getJSONObject(j);
for(int k = 0; k<verse.names().length(); k++){
String verseKey = verse.names().getString(k);
String verseContent = verse.getString(verseKey);
chapterHash.get(i).put(verseKey,verseContent);
}
}
}

Retrieve Array value from JSOn to android client Array

i am doing now retrieving JSON array and assigning it to Android Array String but it failed.
My integer "success" already well. Please help, thank you very much.
My JSON information:
{
"details": [
{
"phone": "89898999",
"name": "Maria"
},
{
"phone": "98983555",
"name": "John"
},
{
"phone": "96969677",
"name": "Leo"
},
{
"phone": "97320099",
"name": "Helen"
},
{
"phone": "90063379",
"name": "Judy"
}
],
"success": 1
}
Android code:
String[] titleArray2;
String[] descriptionArray2;
int cs = 0;
.....
// Create a JSON object from the request response
JSONObject jsonObject = new JSONObject(result);
//Retrieve the data from the JSON object
cs = jsonObject.getInt("success")
JSONArray ja = jsonObject.getJSONArray("details");
for (int i = 0; i < ja.length(); i++)
{
JSONObject jo = (JSONObject) ja.get(i);
titleArray2[i] = jo.getString("phone");
descriptionArray2[i] = jo.getString("name");
}
Your code looks fine, Just try initializing your array
Try like this
JSONArray ja = jsonObject.getJSONArray("details");
titleArray2 =new String[ja.size];
descriptionArray2[i]=new String[ja.size];
and then your for loop.
Mark as right if it works for you. :)

JSON with different structure - Android

I'm getting JSON with different structure. One is with gallery, but other not.
First JSON: (without gallery)
{
"id": "12345",
"title": "titletitle",
"fulltext": "texttext",
"related_articles":[
{
"id": "12346",
"title": "titletitle",
"image_name": "www.example.com/img1.png"
},
{
"id": "12347",
"title": "titletitle",
"image_name": "www.example.com/img2.png"
}
]
}
Second JSON (with gallery)
{
"id": "12345",
"title": "titletitle",
"fulltext": "texttext",
"gallery": [
"www.example.com/img1.png",
"www.example.com/img1.png",
"www.example.com/img1.png",
"www.example.com/img1.pngg",
"www.example.com/img1.png"
],
"related_articles":[
{
"id": "12346",
"title": "titletitle",
"image_name": "www.example.com/img1.png"
},
{
"id": "12347",
"title": "titletitle",
"image_name": "www.example.com/img2.png"
}
]
}
I'm putting this JSON into array like this:
data = whole JSON file, which I get from web service
JSONObject jRealObject = new JSONObject(data);
title = jRealObject.getString("title").toString();
text = jRealObject.getString("fulltext").toString();
JSONArray jArray = jRealObject.getJSONArray("gallery");
for (int i = 0; i < jArray.length(); i++) {
gallery.add(jArray.getString(i));
}
JSONArray jArray = jRealObject.getJSONArray("related_articles");
for (int i = 0; i < jArray.length(); i++) {
jRealObject = jArray.getJSONObject(i);
relatedId[i] = jRealObject.getString("id").toString();
relatedTitle[i] = jRealObject.getString("title").toString();
relatedImage[i] = jRealObject.getString("image_name").toString();
}
So when I get JSON with gallery it works perfect, but when article don't have gallery, I get exception:
W/System.err(30635): org.json.JSONException: No value for gallery
How can I check, if there is "gallery" in JSON ??
You can use the GSON library, this library is a json parse to objects and is very powerfull.
Here You have example for you can implemented this library with you json response.
Tutorial-Android-Parsing-JSON-with-GSON
GSON tutorial
JSONArray jArray = jRealObject.optJSONArray("gallery",null);
if(jArray != null)
for (int i = 0; i < jArray.length(); i++) {
gallery.add(jArray.getString(i));
}

get the index with value using arrayobject and store in array list [duplicate]

This question already has answers here:
get the array index with value using arrayobject and store in array list
(2 answers)
Closed 10 years ago.
[ {
"question_id": 13,
"creation_date": 10,
"name": " certain degrees",
"tags": [
"android",
"sensor"
],
.....
...}
]
Here is the api I want to get the tags array ,the tag array contains only index and value,i want to get the array using array object and finally store in array list, i have tried but fail to get the error has been occured.
02-20 15:45:37.323: I/System.out(1165): org.json.JSONException: Value android at 0 of type java.lang.String cannot be converted to JSONObject
could anybody help me to solve this problem.
tagarray = questionobj.getJSONArray("tags");
for(int j=0;j<tagarray.length();j++){
//tagobject = tagarray.getJSONObject(j);//..if i comment this line the full array list is displaying but i need for each question allocated tags to display..am i clear..
//if(tagobject!=null){
tagname.add(tagarray.getString(j));
///tagname.add(0, null);
//}
}
your json format is not correct
try like that;
{"question":
{"question_id": "13",
"name": "certain degrees",
"tags": [{"android":"N", "sensor":"Y"}]
}}
You can use http://jsonviewer.stack.hu/, to be sure correction of your json data
I sugest you try this code,
import org.json.JSONArray;
import org.json.JSONObject;
public class Main {
public static void main(String[] args) {
String text = "[ { \"question_id\": 13, \"creation_date\": 10, \"name\": \"certain degrees\", \"tags\": [ \"android\", \"sensor\" ] } ]";
System.out.println(text);
JSONArray jsonArray = new JSONArray(text);
JSONObject jsonObjetc = jsonArray.getJSONObject(0);
JSONArray tagarray = jsonObjetc.getJSONArray("tags");
System.out.println(tagarray);
for(int j=0;j<tagarray.length();j++){
System.out.println(tagarray.getString(j));
}
}
}
Good luck, Aron
Try this,
ArrayList<String> list = new ArrayList<String>();
String text = "[ { \"question_id\": 13, \"creation_date\": 10, \"name\": \"certain degrees\", \"tags\": [ \"android\", \"sensor\" ] } ]";
try {
JSONArray jarray = new JSONArray(text);
for (int i = 0; i < jarray.length(); i++) {
JSONArray j_array = jarray.getJSONObject(i)
.getJSONArray("tags");
for (int j = 0; j < j_array.length(); j++) {
String str = j_array.getString(j);
list.add(str);
}
}
} catch (Exception e) {
}
Try This
tagarray = questionobj.getJSONArray("tags");
for(int j=0;j<tagarray.length();j++)
{
tagname.add(tagarray.getJSONObject(j).getString("android"));
}

Categories

Resources