Android convert String to HashMap
android, java, json, regex
Solution
use this method I made:
public HashMap<String, Integer> convertToHashMap(String jsonString) {
HashMap<String, Integer> myHashMap = new HashMap<String, Integer>();
try {
JSONArray jArray = new JSONArray(jsonString);
JSONObject jObject = null;
String keyString=null;
for (int i = 0; i < jArray.length(); i++) {
jObject = jArray.getJSONObject(i);
// beacuse you have only one key-value pair in each object so I have used index 0
keyString = (String)jObject.names().get(0);
myHashMap.put(keyString, jObject.getInt(keyString));
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return myHashMap;
}
use:
String myString = "[ { \"1\":33 }, { \"2\":30 }, { \"3\":15 }, { \"4\":23 }, { \"9\":17 }, { \"U\":2 }, { \"V\":22 }, { \"W\":1 }, { \"X\":35 }, { \"Y\":6 }, { \"Z\":19 } ]";
HashMap<String, Integer> map = convertToHashMap(myString);
Log.d("test", map.toString());
you can also get all keys using `map.keySet()`
Problem
I have a string that is something like this: `[ { "1":33 }, { "2":30 }, { "3":15 }, { "4":23 }, ...{ "9":17 },... { "U":2 }, { "V":22 }, { "W":1 }, { "X":35 }, { "Y":6 }, { "Z":19 } ]` The structure is `{"key":value}`. I need to convert this to a table/HashMap so that I can fetch values based on the key. I tried using Gson but failed. Could there be a simpler method to do it like using some serialization? TIA