我正在使用 volley 从 API 获取响应,但响应由 STATE_ID:STATE_NAME 对 (即值:值对)
组成,我需要不同字符串中的双方值。我需要将这些值放入微调器中,以便在用户选择 State
时我也可以获得其相应的 ID。
// JSON response
{
"1": "West bengal",
"3": "Himachal Pradesh",
"4": "Maharashtra",
"11": "Queensland"
}
我的代码
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);
}
}
最佳答案
正如我们在评论中讨论的那样,您已经有了 iterate()
方法。
做一些能给你带来值(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();
}
请引用this answer中的iterate
方法.我已将此作为新答案发布,因为 OP 无法实现这些值..!!
关于android - 使用双方值解析 JSON,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38199723/