Somnath Pal Somnath Pal - 4 months ago 27
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
State
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";

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void login(View v){
loginRequest();
}
private void loginRequest() {

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

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

};

RequestQueue requestQueue = Volley.newRequestQueue(getApplicationContext());
requestQueue.add(stringRequest);
}
}

Answer

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) {
        e.printStackTrace();
    }

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..!!

Comments