使用双方值解析JSON

Som*_*Pal 5 android json

我正在使用volley来获取API的响应,但响应包含STATE_ID:STATE_NAME对(i.e. value:value pair),我需要在不同的字符串中使用双方的值.我需要将这些值放入微调器中,以便当用户选择时State我也可以获得相应的ID.

// JSON response
{
  "1": "West bengal",
  "3": "Himachal Pradesh",
  "4": "Maharashtra",
  "11": "Queensland"
}
Run Code Online (Sandbox Code Playgroud)

我的守则

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);
    }
}
Run Code Online (Sandbox Code Playgroud)

Jan*_*iya 3

您已经拥有iterate()我们在评论中讨论的方法。

做了一些工作来给你带来价值:

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();
    }
Run Code Online (Sandbox Code Playgroud)

请参考这个答案iterate中的方法。我已将此作为新答案发布,因为 OP 无法实现这些值..!!