Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Parse JSON object with string and value only

I have problem when trying to parse with minimum value to map in Android.

There some sample JSON format with more information ex:

[{id:"1", name:"sql"},{id:"2",name:"android"},{id:"3",name:"mvc"}]

This that example most common to use and easy to use just use getString("id") or getValue("name").

But how do I parse to map using this JSON format with just only string and value minimum format to java map collection using looping. And because the string json will always different one with another. ex:

{"1":"sql", "2":"android", "3":"mvc"}

Thank

like image 971
Edy Cu Avatar asked Dec 10 '10 09:12

Edy Cu


People also ask

How do I parse a string in 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"}');

Can you parse a JSON object?

parse() JSON parsing is the process of converting a JSON object in text format to a Javascript object that can be used inside a program. In Javascript, the standard way to do this is by using the method JSON. parse() , as the Javascript standard specifies.

What is the difference between JSON parse and JSON Stringify?

JSON. parse() is used to convert String to Object. JSON. stringify() is used to convert Object to String.

What is JSON Stringify () method?

The JSON.stringify() method converts a JavaScript value to a JSON string, optionally replacing values if a replacer function is specified or optionally including only the specified properties if a replacer array is specified.


2 Answers

You need to get a list of all the keys, loop over them and add them to your map as shown in the example below:

    String s = "{menu:{\"1\":\"sql\", \"2\":\"android\", \"3\":\"mvc\"}}";
    JSONObject jObject  = new JSONObject(s);
    JSONObject  menu = jObject.getJSONObject("menu");

    Map<String,String> map = new HashMap<String,String>();
    Iterator iter = menu.keys();
    while(iter.hasNext()){
        String key = (String)iter.next();
        String value = menu.getString(key);
        map.put(key,value);
    }
like image 110
dogbane Avatar answered Oct 17 '22 03:10

dogbane


My pseudocode example will be as follows:

JSONArray jsonArray = "[{id:\"1\", name:\"sql\"},{id:\"2\",name:\"android\"},{id:\"3\",name:\"mvc\"}]";
JSON newJson = new JSON();

for (each json in jsonArray) {
    String id = json.get("id");
    String name = json.get("name");

    newJson.put(id, name);
}

return newJson;
like image 11
Buhake Sindi Avatar answered Oct 17 '22 02:10

Buhake Sindi