json对象里面的Json数组和对象

时间:2016-11-13 06:24:53

标签: android json

{
    "status": 200,
    "message": "API executed successfully.",
    "data": [{
        "data": [{
            "shopToken": "NQ2",
            "Id": 5,
            "UserId": 5,
            "ShopName": "test",
            "ContactName": "test",
            "ContactNumber": "test",
            "Address": null,
            "IsActive": true,
            "OwnerName": "Test"
        }],
        "recordsFiltered": 1,
        "recordsTotal": 1,
        "draw": 0,
        "pageIndex": 0,
        "pageSize": 1
    }]
}

如何在Android中解析此JSON?

@Override
protected String doInBackground(Void... voids) {
    OkHttpClient client = new OkHttpClient.Builder().connectTimeout(5, TimeUnit.MINUTES)
        .readTimeout(5, TimeUnit.MINUTES)
        .build();

    Request request = new Request.Builder()
        .url(Config.GLOPOSNET_URL+"getShops?userToken=NQ2")
        .build();

    try {
        Response response = client.newCall(request).execute();
        String res = response.body().string();

                try {
                    JSONObject joa = new JSONObject(res);
                    int status = joa.getInt("status");
                    msg = joa.getString("message");
                    System.out.println("status : "+status);

                    if (status == 200){
                        JSONArray infoa = joa.getJSONArray("data");
                        for (int i=0; i<=infoa.length(); i++){
                            JSONObject johaa = infoa.getJSONObject(i);
                            System.out.println("object=== "+johaa.toString());

                            ModelClassShopList pstShopList = new ModelClassShopList();
                            pstShopList.getShopToken();
                            pstShopList.getId(johaa.getInt("Id"));
                            pstShopList.getUserId(johaa.getString("UserId"));
                            pstShopList.getShopName(johaa.getString("ShopName"));
                            pstShopList.getContactName(johaa.getString("ContactName"));
                            pstShopList.getContactNumber(johaa.getString("ContactNumber"));
                            pstShopList.getAddress(johaa.getString("Address"));
                            pstShopList.getOwnerName(johaa.getString("OwnerName"));

                            String shop_token = pstShopList.getShopToken();
                            String user_name = pstShopList.getShopName(johaa.getString("UserId"));
                            String user_type = pstShopList.getContactName(johaa.getString("UserId"));
                            String user_addres = pstShopList.getContactNumber(johaa.getString("UserId"));


                            System.out.println("shop token=== "+shop_token);

                            SharedPreferences pref = getApplicationContext().getSharedPreferences("MyPref", MODE_PRIVATE);
                            SharedPreferences.Editor editor = pref.edit();
                            editor.putString(Config.SHOP_TOKEN, shop_token);
                            editor.commit();
                        }
                    }else {
                        AlertDialog.Builder builder;
                        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
                            builder = new AlertDialog.Builder(MainActivity.this, android.R.style.Theme_Material_Light_Dialog_Alert);
                            builder.setMessage(""+msg);
                            builder.setCancelable(false);
                            builder.setPositiveButton("Ok", new DialogInterface.OnClickListener() {

                                @Override
                                public void onClick(DialogInterface dialog, int which) {
                                    dialog.dismiss();
                                }
                            });
                            builder.show();
                        }
                    }


                } catch (JSONException e) {
                    e.printStackTrace();
                }
                return res;

            } catch (IOException e) {
                e.printStackTrace();
            }

            return null;
        }

4 个答案:

答案 0 :(得分:3)

从JSON字符串中获取数据数组

 JSONObject jObject = new JSONObject(youStringData);
    JSONArray jArray = jObject.getJSONArray("data");

在第一个数据

中获取数据
 for(int i = 0; i < jArray.length(); i++){
    JSONArray dataTwo = jArray.getJSONObject(i).getJSONArray("data");;
}

如果你想在主对象中获得其他值,你可以使用

jObject.getInt("status")

答案 1 :(得分:2)

试试这个,

// Create JSON object
JSONObject jObject = new JSONObject(res);

// Get the outer "data" array
JSONArray dataOuter = jObject.getJSONArray("data");

// Iterate the outer "data" array
for (int i = 0; i < dataOuter.length() ; i++ ) {
    JSONObject jObject1 = dataOuter.getJSONObject(i);

    // Get the inner "data" array
    JSONArray dataInner = jObject1.getJSONArray("data");

    // Iterate the inner "data" array
    for (int j = 0; j < dataInner.length() ; j++ ) {

        JSONObject jItem = dataInner.getJSONObject(i);
        String shopToken = jItem.getString("shopToken");
        // parse the rest of the items

    }
}

答案 2 :(得分:0)

您可以使用jackson库来解析json。

例如: -

class Student {
   private String name;
   private int age;

   public Student(){}

   public String getName() {
      return name;
   }

   public void setName(String name) {
      this.name = name;
   }

   public int getAge() {
      return age;
   }

   public void setAge(int age) {
      this.age = age;
   }
   public String toString(){
      return "Student [ name: "+name+", age: "+ age+ " ]";
   }
}


public static void main(String args[]){

      ObjectMapper mapper = new ObjectMapper();
      String jsonString = "{\"name\":\"Mahesh\", \"age\":21}";

      //map json to student

      try{
         Student student = mapper.readValue(jsonString, Student.class);

         System.out.println(student);

         mapper.enable(SerializationConfig.Feature.INDENT_OUTPUT);
         jsonString = mapper.writeValueAsString(student);

         System.out.println(jsonString);
      }
      catch (JsonParseException e) { e.printStackTrace();}
      catch (JsonMappingException e) { e.printStackTrace(); }
      catch (IOException e) { e.printStackTrace(); }
   }

参见:http://www.tutorialspoint.com/jackson/

http://www.journaldev.com/2324/jackson-json-java-parser-api-example-tutorial

答案 3 :(得分:0)

你可以使用Gson util来解析任何你想要的json。

    Map<String, List<ErrorInfo>> map = new HashMap<>();
    map.put("ErrorInfos", list);
    Gson gson = new Gson();
    String json = gson.toJson(map);
    Log.i("response", json);

我的json str是:

{"ErrorInfos":[{"errorDetails":"Connect time out"},{"errorDetails":"Connect time out"}]}