1

How to parse a JSON Array,Suppose we have an array given below,how to parse this array in Java,please help me with a code.

[{"guild": "Crimson", "region": "us", "realm": "Caelestrasz", "timestamp": 1311860040}, {"guild": "Crimson", "region": "us", "realm": "Caelestrasz", "timestamp": 1311511740}]
Murtaza Khursheed Hussain
  • 15,176
  • 7
  • 58
  • 83
Gablu
  • 139
  • 3
  • 5
  • 13

3 Answers3

4
String gameJSON = "[{\"guild\": \"Crimson\", \"region\": \"us\", \"realm\": \"Caelestrasz\", \"timestamp\": 1311860040}, {\"guild\": \"Crimson\", \"region\": \"us\", \"realm\": \"Caelestrasz\", \"timestamp\": 1311511740}]";
JSONArray array = new JSONArray(gameJSON);
for (int i = 0; i < array.length(); i++) {
    System.out.println(array.getJSONObject(i));
}
// Access by key : value
for (int i = 0; i < array.length(); i++) {
    JSONObject element = array.getJSONObject(0);
    System.out.format("Player #%d: Realm = %s, Guild = %s\n"
                          , i + 1, element.get("realm"),element.get("guild"));

}

Sample code using the JSON.org lib.

Sahil Muthoo
  • 12,033
  • 2
  • 29
  • 38
  • What did you use library? because I used **Simple.json** and it doesn't support *JSONArray(gameJSON)* . I couldn't find a good library. – Omid Nazifi Apr 13 '13 at 05:23
1

First of all you must have model how to make it ! for example we have 3 object like id , name and family you create a class and name it like

model_phpservice


public class model_phpservice {
    private int id;
    private String name;
    private String family;

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

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

    public String getFamily() {
        return family;
    }

    public void setFamily(String family) {
        this.family = family;
    }
}

after that you must have write a code to parse the codes we name this class

phpservices


public class phpservices {
    private final Context context;
    private static final String TAG = "phpservices";

    public phpservices(Context context) {
        this.context = context;
    }

    public void jsonrequest(final InterFaceData interFaceData) {
    JsonArrayRequest jsonArrayRequest = new
            JsonArrayRequest(Request.Method.GET, "http://yourip/youraddress/",
            null, new Response.Listener<JSONArray>() {
        @Override
        public void onResponse(JSONArray response) {

            List<model_phpservice> CompleteList=new ArrayList<>();
            for (int i = 0; i < response.length(); i++) {
                model_phpservice getmydata=new model_phpservice();
                try{

            JSONObject jsonObject = response.getJSONObject(i);
            getmydata.setId(jsonObject.getInt("id")) ;
            getmydata.setName(jsonObject.getString("name"));
            getmydata.setFamily(jsonObject.getString("family"));
                }catch (JSONException e) {
                    e.printStackTrace();
                    Log.e(TAG, "getdata: "+"getdata errrorrrr" );
                }
            CompleteList.add(getmydata);

        }



            if (CompleteList!=null) {
                Log.i(TAG, "onResponse: " + "itsok");

                interFaceData.oninterface(CompleteList);
            }
        }
    }, new Response.ErrorListener() {
        @Override
        public void onErrorResponse(VolleyError error) {

            Log.e(TAG, "onErrorResponse: "+"not ok" );
        }
    });


        jsonArrayRequest.setRetryPolicy(new DefaultRetryPolicy(8000,DefaultRetryPolicy.DEFAULT_MAX_RETRIES,DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
        RequestQueue requestQueue=Volley.newRequestQueue(context);

        requestQueue.add(jsonArrayRequest);

}

    public interface InterFaceData{
        void oninterface(List<model_phpservice> listtosend);
    }
}

i know maybe its hard to understand but that the correct code

http://yourip/youraddress/ 

you must put your page address that gives you the json code for ip if you test your app in emulator you can find the ip with ipconfig in cmd

and for interface i use it , we need interface to send the list to main activity

and in main activity

public class phpservicesActivity extends AppCompatActivity{
    private static final String TAG = "phpservicesActivity";
    private Button   btn_get;
    private ListView listView;
   // private ProgressBar progress;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_phpservices);

        btn_get=(Button)findViewById(R.id.btn_get);
        listView=(ListView)findViewById(R.id.list_data);
       //progress=(ProgressBar)findViewById(R.id.progress3);


         final phpservices servicesss=new phpservices(this);

         btn_get.setOnClickListener(new View.OnClickListener() {
          @Override
          public void onClick(View view) {
             // progress.setVisibility(View.VISIBLE);
              servicesss.jsonrequest(new phpservices.InterFaceData() {
                  @Override
                  public void oninterface(List<model_phpservice> completelist) {
                      if (listtosend!=null)
                      {
                          Log.i(TAG, "oninterface: "+"interface is ok");

                          adapterff adapter =new adapterff(phpservicesActivity.this,completelist);

                          listView.setAdapter(adapter);

                      }
                      else{
                          Log.e(TAG, "oninterface: "+"error in main activity" );

                      }
                     //progress.setVisibility(View.INVISIBLE);

                  }
              });

                     }
      });

    }

and you need to create to file too 1 the adapter class for conect listview to list and 2 the layout we need to use in listview

1 adapter

1

I'd suggest you use Google Gson, the JSON.org library, or some other Json library for Java.

Further reading:

aioobe
  • 413,195
  • 112
  • 811
  • 826