MangoCool

Json格式数据字符串转List<Map>集合和Map集合

2016-01-11 09:52:51   作者:MangoCool   来源:MangoCool

现在的应用、接口之间传输数据越来越多的倾向于使用json格式数据,因为解析速度快,数据资源占用较小。下面则是为了今后方便自己,而记录的一个json格式数据字符串转list集合和map集合的方法。用到时再也不用抽空重写或者找资料。

StringUtils类:

package com.mangocool.util;

import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import net.sf.json.JsonConfig;

public class StringUtils {
	
	public static List<HashMap<String, String>> json2List(String jsonStr)
	{
		List<HashMap<String, String>> jsonList = new ArrayList<HashMap<String, String>>();
		JSONArray jsonArray = JSONArray.fromObject(jsonStr);
		HashMap<String, String> hashMap = new HashMap<String, String>();
		JsonConfig jc = new JsonConfig();
		jc.setClassMap(hashMap);
		jc.setRootClass(Map.class);
		jc.setArrayMode(JsonConfig.MODE_LIST);
		Collection<HashMap<String, String>> collection = JSONArray.toCollection(jsonArray, jc);
		if(collection instanceof List)
		{
			jsonList = (List<HashMap<String, String>>)collection;
		}
		return jsonList;
	}
	
	public static Map<String, String> json2Map(String jsonStr)
	{
		JSONObject jsonMap = JSONObject.fromObject(jsonStr);
		if(jsonMap instanceof Map)
		{
			return jsonMap;
		}
		return new HashMap<String, String>();
	}

	public static void main(String[] args) {
		String jsonStr = "[{\"id\":\"101\",\"name\":\"zhangsan\"},{\"id\":\"102\",\"name\":\"lisi\"}]";
		System.out.println(json2List(jsonStr));
		jsonStr = "{\"id\":\"103\",\"name\":\"wangwu\",\"age\":\"36\"}";
		System.out.println(json2Map(jsonStr));
	}
}

标签: json list map

分享:

上一篇RHEL6系统安装Greenplum单机版,初始化与测试

下一篇Linux终端下dstat资源监控工具

关于我

崇尚极简,热爱技术,喜欢唱歌,热衷旅行,爱好电子产品的一介码农。

座右铭

当你的才华还撑不起你的野心的时候,你就应该静下心来学习,永不止步!

人生之旅历途甚长,所争决不在一年半月,万不可因此着急失望,招精神之萎葸。

Copyright 2015- 芒果酷(mangocool.com) All rights reserved. 湘ICP备14019394号

免责声明:本网站部分文章转载其他媒体,意在为公众提供免费服务。如有信息侵犯了您的权益,可与本网站联系,本网站将尽快予以撤除。