使用双方值解析JSON

时间:2023-01-15 16:56:31

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.

我正在使用volley来获取API的响应,但响应包含STATE_ID:STATE_NAME对(即值:值对),我需要不同字符串中的两个值。我需要将这些值放入微调器中,以便当用户选择状态时,我也可以获得相应的ID。

// 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);
    }
}

5 个解决方案

#1


2  

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

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

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

请参考此答案中的iterate方法。我发布了这个作为一个新的答案,因为OP无法为价值观做出准备.. !!

#2


2  

I used iterator to find a key. May this will help:

我使用迭代器来查找密钥。愿这有助于:

 private void parseRespone(String response){

try {

JSONObject MainjsonObject = new JSONObject(response)

Iterator<String> iter= MainjsonObject.keys();
//To get keys of an object

    while (iter.hasNext()) 
    {

    String key = (String)iter.next();

            //Object value = jsonobj.get(key);  //To use by object

        String valueStr = jsonobj.get.getString(key);


    Log.i("Jsonparsing", "key= "+key + "\n Value=" +valueStr );

    Toast.makeText(getActivity(),"key= "+ key + "\n value= " + valueStr ,Toast.LENGTH_SHORT).show();        

    }

    } catch (JSONException e) {
        e.printStackTrace();
    }catch (Exception e) {
        e.printStackTrace();
    }
}

I could find an unknown key by this. Please check in a Log in your android studio... here I have put Toast also..

我可以找到一个未知的密钥。请登录你的Android工作室登录...在这里我也把Toast也放了..

And call this function here...

并在这里调用此功能......

...........
        @Override
                    public void onResponse(String response) {

            parseRespone(response);  //Function to parse json

                    }

Thanks..

#3


1  

It will be much better if you consider changing your response to something like this:

如果您考虑将响应更改为以下内容会更好:

[
  {"ID":"1","name": "West bengal"},
  {"ID":"3","name": "Himachal Pradesh"},
  {"ID":"4","name": "Maharashtra"},
  {"ID":"11","name": "Queensland"}
]

#4


1  

You can use jsonObject.names() (or keys() for an Iterator) to retrieve all keys. After that you can iterate through the array using the keys and store your strings.

您可以使用jsonObject.names()(或Iterator的keys())来检索所有键。之后,您可以使用键遍历数组并存储字符串。

https://developer.android.com/reference/org/json/JSONObject.html#names() https://developer.android.com/reference/org/json/JSONObject.html#keys()

#5


0  

I tried this solution and it worked out.`Here, "key" will toast the key_value[1,3,4,11] and value will print the names[West bengal,Himachal Pradesh,Maharashtra,Queensland].

我尝试了这个解决方案并且解决了问题。在这里,“关键”将向key_value [1,3,4,11]致敬,值将打印出名称[West bengal,Himachal Pradesh,Maharashtra,Queensland]。

JSONObject list_object = inner_json_object.getJSONObject("");

JSONObject list_object = inner_json_object.getJSONObject(“”);

                for (String key : iterate(list_object.keys()))
                {
                    // here key will be containing your OBJECT NAME YOU CAN SET IT IN TEXTVIEW.
                    Toast.makeText(Activity.this, ""+key, Toast.LENGTH_SHORT).show();
                    String value = bank_list_object.optString(key);


                }`



private <T> Iterable<T> iterate(final Iterator<T> i){
    return new Iterable<T>() {
        @Override
        public Iterator<T> iterator() {
            return i;
        }
    };
}

#1


2  

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

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

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

请参考此答案中的iterate方法。我发布了这个作为一个新的答案,因为OP无法为价值观做出准备.. !!

#2


2  

I used iterator to find a key. May this will help:

我使用迭代器来查找密钥。愿这有助于:

 private void parseRespone(String response){

try {

JSONObject MainjsonObject = new JSONObject(response)

Iterator<String> iter= MainjsonObject.keys();
//To get keys of an object

    while (iter.hasNext()) 
    {

    String key = (String)iter.next();

            //Object value = jsonobj.get(key);  //To use by object

        String valueStr = jsonobj.get.getString(key);


    Log.i("Jsonparsing", "key= "+key + "\n Value=" +valueStr );

    Toast.makeText(getActivity(),"key= "+ key + "\n value= " + valueStr ,Toast.LENGTH_SHORT).show();        

    }

    } catch (JSONException e) {
        e.printStackTrace();
    }catch (Exception e) {
        e.printStackTrace();
    }
}

I could find an unknown key by this. Please check in a Log in your android studio... here I have put Toast also..

我可以找到一个未知的密钥。请登录你的Android工作室登录...在这里我也把Toast也放了..

And call this function here...

并在这里调用此功能......

...........
        @Override
                    public void onResponse(String response) {

            parseRespone(response);  //Function to parse json

                    }

Thanks..

#3


1  

It will be much better if you consider changing your response to something like this:

如果您考虑将响应更改为以下内容会更好:

[
  {"ID":"1","name": "West bengal"},
  {"ID":"3","name": "Himachal Pradesh"},
  {"ID":"4","name": "Maharashtra"},
  {"ID":"11","name": "Queensland"}
]

#4


1  

You can use jsonObject.names() (or keys() for an Iterator) to retrieve all keys. After that you can iterate through the array using the keys and store your strings.

您可以使用jsonObject.names()(或Iterator的keys())来检索所有键。之后,您可以使用键遍历数组并存储字符串。

https://developer.android.com/reference/org/json/JSONObject.html#names() https://developer.android.com/reference/org/json/JSONObject.html#keys()

#5


0  

I tried this solution and it worked out.`Here, "key" will toast the key_value[1,3,4,11] and value will print the names[West bengal,Himachal Pradesh,Maharashtra,Queensland].

我尝试了这个解决方案并且解决了问题。在这里,“关键”将向key_value [1,3,4,11]致敬,值将打印出名称[West bengal,Himachal Pradesh,Maharashtra,Queensland]。

JSONObject list_object = inner_json_object.getJSONObject("");

JSONObject list_object = inner_json_object.getJSONObject(“”);

                for (String key : iterate(list_object.keys()))
                {
                    // here key will be containing your OBJECT NAME YOU CAN SET IT IN TEXTVIEW.
                    Toast.makeText(Activity.this, ""+key, Toast.LENGTH_SHORT).show();
                    String value = bank_list_object.optString(key);


                }`



private <T> Iterable<T> iterate(final Iterator<T> i){
    return new Iterable<T>() {
        @Override
        public Iterator<T> iterator() {
            return i;
        }
    };
}