日期:2014-05-20  浏览次数:20693 次

写一个函数,如何把字符串转换成Map对象
问题,写一个函数,传入一个字符串,把这个的字符串转换成Map对象。
在字符串中不允许出现特殊的字符,这个不用做检查(只要传入的时候符合要求就可以了)

函数签名如下:
public static Object unpack(String value) throws Exception{
。。。。。
}

例如 String str = "{eror=34,list=[{id=99,bondcd=6},{id=98,bondcd=7}],over=345}";

Map map1 = new HashMap();
map1.put("id","99");
map1.put("bondcd","6");

Map map2 = new HashMap();
map2.put("id","98");
map2.put("bondcd","7");

List list = new ArrayList();
list.add(map1);
list.add(map2);

Map map = new HashMap();
map.put("eror","34");
map.put("list",list);
map.put("over","345");

我最后需要是map这个对象,也就是unpack()这个函数返回的是map这个对象(注意函数签名中的返回值必须是Object)

说明,提供的字符串的格式都是key=value格式的,用","隔开。如果返回的Map对象中的key值是字符串,value值可以是字符串,也可以是List集合(一般是ArrayList),而list集合中的元素一般是map对象
java

------解决方案--------------------
明明是一个Json串,非得返回map的形式。。。
------解决方案--------------------
引用:
明明是一个Json串,非得返回map的形式。。。

是啊,推荐楼主参见这个链接看看
http://hi.baidu.com/liwei45212/item/e07ae6cd163def2bef466554
希望能够帮到你
------解决方案--------------------
/**
 * @param args
 */
public static void main(String[] args) {
// TODO Auto-generated method stub

String str = "{eror=34,list=[{id=99,bondcd=6},{id=98,bondcd=7}],over=345}";
Map<String,Object> rightLlist = new Gson().fromJson(str,new TypeToken<Map<String,Object>>() {}.getType());
for(Entry e : rightLlist.entrySet()){
String value = e.getValue().toString();
try {
List<Map<String,String>> list = new Gson().fromJson(value,new TypeToken<List<Map<String,String>>>() {}.getType());
e.setValue(list);
} catch (JsonSyntaxException e1) {

}
}
System.out.println(((List<Map<String,Object>>)rightLlist.get("list")).get(0).get("id"));