我有一个从mp获得的arraylist如下,
ArrayList<String> aList = (ArrayList<String>) jsonMap.get("govIds");
arraylist的大小为1,其内容为fooles,
[{govId=023402094, govIdType=TEST}]
如何使用govId = 023402094作为一个字符串对象并将govIdType = TEST作为另一个字符串对象,将arraylist的大小设为2。
或如何使[{govId = 023402094,govIdType = TEST}]作为键(String)-value(String)(再次是一个map)对。
由于
答案 0 :(得分:0)
试试这个:
//here is the test data
String s="[{govId=023402094, govIdType=TEST}]";
List<String> aList =new ArrayList<String>();
aList.add(s);
//end of test data
//Here is what you need begins
String text=aList.get(0).replaceAll("[\\[\\]\\{\\}]", "");// remove the char "{","}","[" and "]"
//now the text is :govId=023402094, govIdType=TEST
String[] values=text.split(",");
List resultList=new ArrayList<String>();//Convert to another list, you can if you want to change a little to change into a map
for(String value:values){
resultList.add(value);
}
//test the result
System.out.println(resultList);//[govId=023402094, govIdType=TEST]
如果您的字符串格式看起来像JSON {key1:value,key2:value2};您可以使用Gson轻松将其更改为地图:
public static void main(String[] args){
String s="[{govId:023402094, govIdType:TEST}]";// something like this
String text=s.replaceAll("[\\[\\]]", "");// remove the char "[" and "]" to make it like as JSON format
Map<String,String> map=toMapUsingGSON(text));
}
private static Map<String,String> toMapUsingGSON(String json){
Type mapType = new TypeToken<Map<String, String>>(){}.getType();
return new Gson().fromJson(json, mapType);
}