背景:有时候string类型的数据取出来是个很标准的key、value形式,通过Gson的可以直接转成map
使用方式:
Gson gson = new Gson();
Map<String, Object> map = new HashMap<String, Object>();
map = gson.fromJson(jsonString, map.getClass());#关键
String goodsid=(String) map.get("goods_id");
System.out.println("map的值为:"+goodsid);
jsong数据为:
{"goods_id":"140861765","cat_id":"210","goods_sn":"171073501","goods_sn_back":"171073501","goods_upc":null,"goods_name":"Lace-Up Boxer Swimming Trunks"}
是个很标准的key,value形式,转换后,在使用map分得到key,打印的map为
Gson的另外一种写法
public static Map<String, Object> json2map(String str_json) { Map<String, Object> res = null; try { Gson gson = new Gson(); res = gson.fromJson(str_json, new TypeToken<Map<String, Object>>() { }.getType()); } catch (JsonSyntaxException e) { } return res; }
gson在mavent的配置
<!-- 配置gson --> <dependency> <groupId>com.google.code.gson</groupId> <artifactId>gson</artifactId> <version>2.2.4</version> </dependency>