Somnath Pal Somnath Pal - 1 year ago 83
JSON Question

Parse JSON with both sides values

I'm using volley to get response from API but the response consist of STATE_ID:STATE_NAME pair

(i.e. value:value pair)
and I need both side's values in different Strings. I need these values to put in a spinner so that when user selects a
I can get its corresponding ID also.

// JSON response
"1": "West bengal",
"3": "Himachal Pradesh",
"4": "Maharashtra",
"11": "Queensland"

My Code

public class MainActivity extends AppCompatActivity {

private static final String STATE = "MY_API";

protected void onCreate(Bundle savedInstanceState) {
public void login(View v){
private void loginRequest() {

StringRequest stringRequest = new StringRequest(Request.Method.POST, STATE,
new Response.Listener<String>() {
public void onResponse(String response) {

Toast.makeText(MainActivity.this, response, Toast.LENGTH_SHORT).show();
}, new Response.ErrorListener() {
public void onErrorResponse(VolleyError error) {
Toast.makeText(getApplicationContext(), "VolleyError" + error.toString(), Toast.LENGTH_LONG).show();
}) {
protected Map<String, String> getParams() {
Map<String, String> params = new HashMap<String, String>();
return params;


RequestQueue requestQueue = Volley.newRequestQueue(getApplicationContext());

Answer Source

You already have the iterate() method as we discussed in comments.

Done some work to give you value :

try {
        JSONObject jsonObject = new JSONObject(response);

        for (String key : iterate(jsonObject.keys()))
            Toast.makeText(this, "Key : "+key+" Value: "+jsonObject.optString(key), Toast.LENGTH_SHORT).show();
    } catch (JSONException e) {

Please refer the iterate method from this answer. I have posted this as a new answer because OP was unable to make it for the values..!!

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download