如何使用url在android中解析这个json数组?

时间:2014-06-30 06:02:52

标签: android json parsing arrays jsonobject

我正在尝试解析多个json数组,其中包含嵌套的json arrys。我搜索了很多,但无法准确理解该怎么做。我已经完成了以下代码,但它没有给我所有的值。

到目前为止,我已完成此编码,result字符串显示items arrayjArray显示questions array。我是json的新手,因此请一步一步帮助我。

 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 */
      }
  ]

3 个答案:

答案 0 :(得分:1)

这是你的hierarcy json数据

[
    {
        "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");
            //......
        }
    }

答案 1 :(得分:0)

从以下链接下载Gson Google Gson 2.2.4 jar

在你的libs文件夹中添加jar

为Json Response创建一个Object类。对于上面的响应,Objects类如下所示,

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;
}

}

复制项目中的上述课程

调用Webservice,如下所示

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

    }
}

}

答案 2 :(得分:0)

使用GSON Google图书馆进行JSON表示。您可以为每个JSON元素创建一个Java类,并将JSON字符串表示直接转换为Java对象,这非常简单。以下是反序列化类别列表字符串的示例snnipet:

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;
    }
}

以下是您的类别java类

的方式
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;
    }
}

当然,您可以将Java对象包含为另一个Java对象的成员。例如,在主json字符串中,Category必须是java对象的数组变量:

public class SampleModel {

    private ItemModel[] items;
    private CategoryModel[] categories;
    private Date category_Timestamp;
    private QuestionModel[] questions;
    private Date question_Timestamp;

    // All getters and setters
    ...
}