john1717 john1717 - 1 month ago 8
Java Question

java - how to parse String back to List of Map

I have a String with this format (it's a List of Map assigned to a string var)

[{code=1, data=Male} , {code=2, data=Female}]


.. how can I parse the above string back to list of map.. without using any String.split function (cause it is prone to error)

any help please? thanks :)

here is the code I've tried.. but with split function..

if(!string.equals("")){
String[] listArray = string.split(DELIMITER);
for (int i=0;i<listArray.length;i++) {
String val=listArray[i];
val = val.replaceAll("[\\{\\}]", "");

//Gets the value from DATA key
if(val.split(EQDELIMITER)[0].trim().equalsIgnoreCase("DATA")){
try{
map.put("DATA", val.split(EQDELIMITER)[1]);
}catch(IndexOutOfBoundsException e){
map.put("DATA", "");
}
}
//Gets the value from CODE key
if(val.split(EQDELIMITER)[0].trim().equalsIgnoreCase("CODE")){

try{
map.put("CODE", val.split(EQDELIMITER)[1]);
}catch(IndexOutOfBoundsException e){
map.put("CODE", "");
}

}


if (map != null && map.size() >= 2) {
//add map to codeList
codeList.add(map);
map = new HashMap<String,Object>();
}
}
}

Answer

If you are flexible enough to use a library, then Use google's GSON

Map map = gson.fromJson(jsonString, Map.class);

As you want a list of Map, wo you can also use TypeToken

List<Map<E,V>> list= new Gson().fromJson(jsonString, 
                           new TypeToken<List<Map<E, V>>() {}.getType());

replace E, V with actual types.

Comments