Reputation: 1622
I am trying to parse more than one json array which consists of nested json arrys. I have googled a lot but couldn't understand exactly what to do. I have done the following code but it doesn't give me all the values.
I have done this coding so far and the result
string displays items array
and the jArray
displays questions array
. I am totally new to json and hence please help me step by step.
String result = null;
InputStream is = null;
try{
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("url");
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
is = entity.getContent();
Log.e("log_tag", "connection success "+"nameValuePairs");
}
catch(Exception e)
{
Log.e("log_tag", "Error in http connection "+e.toString());
}
try
{
BufferedReader reader = new BufferedReader(new InputStreamReader(is,HTTP.UTF_8),8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null)
{
sb.append(line + "\n");
}
is.close();
result=sb.toString();
Log.e("log_tag", "result "+result.toString());
}
catch(Exception e)
{
Log.e("log_tag", "Error converting result "+e.toString());
}
try
{
JSONArray jArray=new JSONArray(result);
Log.w("Lengh",""+jArray);
String s="",s1,s2,s3,s4,s5,s6,s7,s8,s9;
Log.w("Lengh",""+jArray.length());
for(int i=0;i<jArray.length();i++){
JSONArray newarr = jArray.getJSONObject(i).getJSONArray("items");
Log.w("Lengh",""+newarr.length());
for(int j= 0; j<newarr.length();j++){
JSONObject json_data = newarr.getJSONObject(i);
s=json_data.getString("id");
Log.w("parsed data",""+s);
// System.out.println("Id is: "+ s);
}
}
}
catch(JSONException e)
{
Log.e("log_tag", "Error parsing data "+e.toString());
}
Json Array
[
{
"items": [
{
"id": "11",
"Item_Id": "123",
"Item_Name": "Chicken Cream Soup",
"Price": "8",
"Currency": "AED",
"Category": "Soup",
"Description": "Creamy Chicken Soup with garnish & side helpings",
"Unit": "2",
"food_type": "Non",
"Image_Large": "/images_large/chickensoup.jpg",
"Image_Thumb": "/images_large/chickensoup.jpg",
"Timestamp": "6/23/2014 9:49:43 PM",
"Promotion": "",
"Item_Name_arabic": "حساء الطماطم",
"Item_Name_russian": "",
"Currency_arabic": "درهم",
"Currency_russian": "",
"Description_arabic": "حساء الطماطم",
"Description_russian": "",
"Note": "",
"Nutritional_info": "",
"extrafield_1": "",
"extrafield_2": "",
"preferncess": [
"No Salt",
"Extra Sugar"
],
"preferncess_ids": [
"1",
"2"
],
"price": [
"4",
"5"
],
"preferncess_arabic": [
"لا الملح",
"سكر اضافية"
]
},
{
"id": "12",
"Item_Id": "501",
"Item_Name": "Pasta Napolitan",
"Price": "18",
"Currency": "AED",
"Category": "Pasta",
"Description": "Pasta in Napolitan Sauce",
"Unit": "20",
"food_type": "Non",
"Image_Large": "/images_large/pasta.jpg",
"Image_Thumb": "/images_large/pasta.jpg",
"Timestamp": "6/23/2014 9:47:45 PM",
"Promotion": "",
"Item_Name_arabic": "حساء الطماطم",
"Item_Name_russian": "",
"Currency_arabic": "درهم",
"Currency_russian": "",
"Description_arabic": "حساء الطماطم",
"Description_russian": "",
"Note": "",
"Nutritional_info": "",
"extrafield_1": "",
"extrafield_2": "",
"preferncess": [
"No Salt"
],
"preferncess_ids": [
"3"
],
"price": [
"5"
],
"preferncess_arabic": [
"لا الملح"
]
},
/* values till id =25 are present */
],
"categories": [
{
"categoryName": "Salads",
"categoryShortName": "Salads",
"catid": "0",
"categoryArabicName": "سلطة خضراء"
},
{
"categoryName": "Mezzah",
"categoryShortName": "Mezzah",
"catid": "1",
"categoryArabicName": "المزة"
},
/* some more values present */
"questions": [
{
"q_id": "1",
"q_question": "How would you rate our Menu ?",
"q_option1": "Excellent",
"q_option2": "Very Good",
"q_option3": "Good",
"q_option4": "Bad",
"q_option5": "Terrible",
"Timestamp": "9/12/2013 3:31:55 PM",
"q_status": "1"
},
{
"q_id": "2",
"q_question": "How would you rate our presentation, taste and quality of food ?",
"q_option1": "Excellent",
"q_option2": "Very Good",
"q_option3": "Good",
"q_option4": "Bad",
"q_option5": "Terrible",
"Timestamp": "9/12/2013 3:31:55 PM",
"q_status": "1"
},
/* some more values present */
}
]
Upvotes: 0
Views: 1984
Reputation: 1867
here is your hierarcy json data
[
{
"items":+[15],
"categories":+[6],
"category_Timestamp":"6/24/2014 1:05:28 PM",
"questions":+[5],
"question_Timestamp":"9/12/2013 3:31:55 PM"
}
]
here is the code to parse entire data create Core Objects of items and categories and questions as you like..
//for parsing the given json data
private void parseEntireData(String url) throws JSONException {
JSONArray jArray=new JSONArray(url);
String[] metaData={"items","categories","category_Timestamp","questions","question_Timestamp"};
for(int i=0;i<jArray.length();i++){
JSONObject json_data = jArray.getJSONObject(i);
switch(i){
case 0 : parseItems(json_data);break;
case 1 : parseCategories(json_data);break;
case 2: json_data.getString(metaData[i]);break;
case 3: parseQuestion(json_data); break;
case 4: json_data.getString(metaData[i]);break;
}
}
}
// for parsing question
private void parseQuestion(JSONObject json_data) throws JSONException {
JSONArray jArray=json_data.getJSONArray("question");
for(int i=0;i<jArray.length();i++){
// parse data...
String _id=json_data.getString("id");
//......
}
}
// for parsing categories
private void parseCategories(JSONObject json_data) throws JSONException {
JSONArray jArray=json_data.getJSONArray("categories");
for(int i=0;i<jArray.length();i++){
// parse data...
String _id=json_data.getString("categoryName");
//......
}
}
// for parsing items private void parseItems(JSONObject json_data) throws JSONException { JSONArray jArray=json_data.getJSONArray("items"); for(int i=0;i<jArray.length();i++){ // parse data... String _id=json_data.getString("q_id"); //...... } }
Upvotes: 1
Reputation: 344
Use GSON google library for JSON representation. You may create a Java class for each JSON element, and convert JSON string representation to Java object directly, is really easy. Here is a sample snnipet of deserializing a string of Category list:
public static CategoryModel[] deserializeCategoriesData(String jsonData) throws Exception {
try {
Log.d(LOGTAG, "Deserialize JSON for Category list");
return setUpGsonBuilder().fromJson(jsonData, CategoryModel[].class);
} catch (Exception e) {
Log.e(LOGTAG, "Error reading category json", e);
throw e;
}
}
And here is how your Category java class would be
public class CategoryModel {
private String categoryName;
private String categoryShortName;
private int catid;
private String categoryArabicName;
public String getCategoryName() {
return categoryName;
}
public void setCategoryName(String categoryName) {
this.categoryName = categoryName;
}
public String getCategoryShortName() {
return categoryShortName;
}
public void setCategoryShortName(String categoryShortName) {
this.categoryShortName = categoryShortName;
}
public int getCatid() {
return catid;
}
public void setCatid(int catid) {
this.catid = catid;
}
public String getCategoryArabicName() {
return categoryArabicName;
}
public void setCategoryArabicName(String categoryArabicName) {
this.categoryArabicName = categoryArabicName;
}
}
Of course, you can include a Java object as a member of another one. For example, in your main json string, Category must be a array variable of your java object as it:
public class SampleModel {
private ItemModel[] items;
private CategoryModel[] categories;
private Date category_Timestamp;
private QuestionModel[] questions;
private Date question_Timestamp;
// All getters and setters
...
}
Upvotes: 0
Reputation: 7753
Download Gson From the following link Google Gson 2.2.4 jar
Add the jar in your libs folder
Create an Object class for your Json Response. For the above response the Objects class is shown below,
import java.util.List;
public class ResponeItem {
public List<Item> items;
public List<Category> categories;
public String category_Timestamp;
public List<Question> questions;
public String question_Timestamp;
public class Item {
public String id;
public String Item_Id;
public String Item_Name;
public String Price;
public String Currency;
public String Category;
public String Description;
public String Unit;
public String food_type;
public String Image_Large;
public String Image_Thumb;
public String Timestamp;
public String Promotion;
public String Item_Name_arabic;
public String Item_Name_russian;
public String Currency_arabic;
public String Currency_russian;
public String Description_arabic;
public String Description_russian;
public String Note;
public String Nutritional_info;
public String extrafield_1;
public String extrafield_2;
public List<String> preferncess;
public List<String> preferncess_ids;
public List<String> price;
public List<String> preferncess_arabic;
}
public class Category {
public String categoryName;
public String categoryShortName;
public String catid;
public String categoryArabicName;
}
public class Question {
public String q_id;
public String q_question;
public String q_option1;
public String q_option2;
public String q_option3;
public String q_option4;
public String q_option5;
public String Timestamp;
public String q_status;
}
}
Copy the above class in your project
Call the Webservice like below,
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.util.List;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import com.google.gson.Gson;
import android.app.Activity;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
public class ResponseActivity extends Activity{
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(-Your layout id-)
//Initializations
new NetworkCallTask().execute("Your-Url");
}
class NetworkCallTask extends AsyncTask<String, Void, InputStream> {
@Override
protected void onPreExecute() {
super.onPreExecute();
// Show your progressbar or something..
}
@Override
protected InputStream doInBackground(String... url) {
DefaultHttpClient client = new DefaultHttpClient();
HttpGet getRequest = new HttpGet(url[0]);
try {
HttpResponse getResponse = client.execute(getRequest);
final int statusCode = getResponse.getStatusLine()
.getStatusCode();
if (statusCode != HttpStatus.SC_OK) {
Log.w(getClass().getSimpleName(), "Error " + statusCode
+ " for URL " + url[0]);
return null;
}
HttpEntity getResponseEntity = getResponse.getEntity();
return getResponseEntity.getContent();
} catch (IOException e) {
getRequest.abort();
Log.w(getClass().getSimpleName(), "Error for URL " + url[0], e);
}
return null;
}
@Override
protected void onPostExecute(InputStream result) {
super.onPostExecute(result);
if (result != null) {
Gson gson = new Gson();
Reader reader = new InputStreamReader(result);
ResponeItem response = gson.fromJson(reader,
ResponeItem.class);
//You can access all the objects here
List<Item> items = response.items;
List<Category> categories = response.categories;
String category_Timestamp = response.category_Timestamp;
List<Question> questions = response.questions;
String question_Timestamp = response.question_Timestamp;
} else {
Log.e(getClass().getSimpleName(), "Server Error");
}
// Dissmiss your progressbar
}
}
}
Upvotes: 0