-3
{
    "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
    }]
}

How can I parse this JSON in Android?

@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;
        }
3
  • didnt get your answer? from where you are passing php , java ...? Commented Nov 13, 2016 at 6:26
  • not yet.. i am parsing from android Commented Nov 13, 2016 at 6:27
  • still confused to take data array-object inside data. Commented Nov 13, 2016 at 6:30

4 Answers 4

3

To get data array from your JSON String

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

to get the data inside first one data

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

if you want to get other value in the main object you can use

jObject.getInt("status")
Sign up to request clarification or add additional context in comments.

3 Comments

This is close. I believe the question asked about the data array inside the first data array.
if possible then give me idea to get another "data" inside data.
ok , I will update my answer
2

Try this,

// 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 Comments

Thanks @k neeraj lal.... i have solved my question with ur help (y)
@BhavyaGusai Accept the answer if it helped you :)
0

You can use Gson util to parse json whatever you want .

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

And my json str is :

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

Comments

0

You can use jackson libraries to parse json.

Eg:-

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

Refer:http://www.tutorialspoint.com/jackson/

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

5 Comments

i am trying with okhttp library.. if you have any idea for that then share with me pls..
I think jakson is the popular library and simple tool. Use that for your work.
@cricket_007: Done. Thanks your comment.
Well, it would be more useful to answer the actual question, than your simple example.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.