Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Parse JSON with both sides values

Tags:

json

android

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);
    }
}
like image 556
Somnath Pal Avatar asked Jul 05 '16 09:07

Somnath Pal


People also ask

What is JSON parse () method?

The JSON.parse() method parses a JSON string, constructing the JavaScript value or object described by the string. An optional reviver function can be provided to perform a transformation on the resulting object before it is returned.

What is difference between JSON parse and JSON Stringify?

The JSON. parse() function is used to convert a string into a JavaScript object while the JSON. stringify() function is used to convert a JavaScript object into a string.

How do you parse an array of JSON objects?

Example - Parsing JSON Use the JavaScript function JSON.parse() to convert text into a JavaScript object: const obj = JSON.parse('{"name":"John", "age":30, "city":"New York"}'); Make sure the text is in JSON format, or else you will get a syntax error.

Can you have backslash in JSON?

The escape character works in a different was when used with JSON data in a file as compared to a CSV file. In order to escape the the quotes enclosing around word Bengaluru, we need to give a backslash character \ in front of quotes ( \"Bengaluru\" ) in the JSON data file before we upload it to the stage.


2 Answers

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

like image 135
Janki Gadhiya Avatar answered Sep 25 '22 20:09

Janki Gadhiya


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

And call this function here...

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

            parseRespone(response);  //Function to parse json

                    }

Thanks..

like image 32
Kush Avatar answered Sep 25 '22 20:09

Kush