如何把JSON对象转为map对象呢?
JSON 对象保存在大括号内。JavaScript中, 多个对象可以保存 键/值 对。Map对象保存键/值对,是键/值对的集合。任何值(对象或原始值) 可作为键或值。Object结构对应字符串-值,Map结构对应于值-值。
javascript将JSON对象转为map可以用阿里巴巴包装的对象FastJSON转换的方法有很多,比如使用JSON类的parseObject来解析JSON转换和使用字符串JSONObject类的parse方法来解析JSON字符串等。
javascript将JSON对象转为map对象实例:packagecom.zkn.newlearn.json;
importcom.alibaba.fastjson.JSON;
importcom.alibaba.fastjson.JSONObject;
importjava.util.Map;
/**
*JSON自动转换字符串
*Createdbyzknon2016/8/22.
*/
publicclassJsonToMapTest01{
publicstaticvoidmain(String[]args){
Stringstr={0zhangsanlisiwangwumaliu”}”;
//第一种方式
Mapmaps=(Map)JSON.parse(str);
System.out.println(这是用的JSON类来解析JSON字符串!
for(Objectmap:maps.entrySet()){
System.out.println(((Map.Entry)map).getKey() “” ((Map.Entry)map).getValue());
}
//第二种方式
MapmapTypes=JSON.parseObject(str);
System.out.println(这是用的JSON类的parseObject来解析JSON字符串!
for(Objectobj:mapTypes.keySet()){
System.out.println(“key为:” obj “值为:” mapTypes.get(obj));
}
//第三种方式
MapmapType=JSON.parseObject(str,Map.class);
System.out.println(这是用的JSON指定分析类型进行分析JSON字符串!
for(Objectobj:mapType.keySet()){
System.out.println(“key为:” obj “值为:” mapType.get(obj));
}
//第四种方式
/**
*JSONObject是Map接口实现类
*/
Mapjson=(Map)JSONObject.parse(str);
System.out.println(这是用的JSONObject类的parse方法来解析JSON字符串!
for(Objectmap:json.entrySet()){
System.out.println(((Map.Entry)map).getKey() “” ((Map.Entry)map).getValue());
}
//第五种方式
/**
*JSONObject是Map接口实现类
*/
JSONObjectjsonObject=JSONObject.parseObject(str);
System.out.println(这是用的JSONObject的parseObject方法来解析JSON字符串!
for(Objectmap:json.entrySet()){
System.out.println(((Map.Entry)map).getKey() “” ((Map.Entry)map).getValue());
}
//第六种方式
/**
*JSONObject是Map接口实现类
*/
MapmapObj=JSONObject.parseObject(str,Map.class);
System.out.println(“这个是用JSONObject的parseObject方法和实施返回类型分析JSON字符串!
for(Objectmap:json.entrySet()){
System.out.println(((Map.Entry)map).getKey() “” ((Map.Entry)map).getValue());
}
StringstrArr=“{ {“0”:“zhangsanlisiwangwumaliu”},”
{00zhangsanlisiwangwu三三:maliu”}}”;
//JSONArray.parse()
System.out.println(json);
}
}