Java中String类型转换成Map

转自:https://www.cnblogs.com/chongyou/p/7466039.html

背景:有时候string类型的数据取出来是个很标准的key、value形式,通过Gson的可以直接转成map

使用方式:

1 Gson gson = new Gson();
2 Map<String, Object> map = new HashMap<String, Object>();
3 map = gson.fromJson(jsonString, map.getClass());#关键
4 String goodsid=(String) map.get("goods_id");
5 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的另外一种写法

 1 public static Map<String, Object> json2map(String str_json) {
 2         Map<String, Object> res = null;
 3         try {
 4             Gson gson = new Gson();
 5             res = gson.fromJson(str_json, new TypeToken<Map<String, Object>>() {
 6             }.getType());
 7         } catch (JsonSyntaxException e) {
 8         }
 9         return res;
10 }

gson在mavent的配置

1 <!-- 配置gson -->
2     <dependency>
3         <groupId>com.google.code.gson</groupId>
4         <artifactId>gson</artifactId>
5         <version>2.2.4</version>
6     </dependency>

 

posted @ 2019-10-31 11:32  NemoWang  阅读(91946)  评论(3编辑  收藏  举报