惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

博客园_首页
博客园 - 【当耐特】
博客园 - 叶小钗
阮一峰的网络日志
阮一峰的网络日志
WordPress大学
WordPress大学
D
Docker
T
The Blog of Author Tim Ferriss
Cyber Security Advisories - MS-ISAC
Cyber Security Advisories - MS-ISAC
Microsoft Azure Blog
Microsoft Azure Blog
钛媒体:引领未来商业与生活新知
钛媒体:引领未来商业与生活新知
月光博客
月光博客
M
MIT News - Artificial intelligence
H
Hackread – Cybersecurity News, Data Breaches, AI and More
freeCodeCamp Programming Tutorials: Python, JavaScript, Git & More
云风的 BLOG
云风的 BLOG
F
Fortinet All Blogs
罗磊的独立博客
小众软件
小众软件
A
About on SuperTechFans
MyScale Blog
MyScale Blog
D
DataBreaches.Net
The GitHub Blog
The GitHub Blog
C
Check Point Blog
L
LangChain Blog

博客园 - Bryan Wong

Pushlets的初始化陷阱 在Tomcat部署Solr 4.3 Spring Security如何防止会话固定攻击(session fixation attack) Jdk自带的定时任务TimerTask和ScheduledExecutorService及其在Spring中的集成 Lucene索引,查询及高亮显示 蛋疼的腾讯微博数据类型和API文档 语言检测工具language-detection 你所不知道的Quartz特性 Spring Data集成MongoDB访问 Jetty的jar包依赖关系图 CAPS & BHCA Java中的集合类图 下载SUSE Linux 10 sp1的经历好曲折 C#代码检查工具:stylecop 圈复杂度基础 Scrum——“鸡”和“猪”的寓言 使用java断言调测程序 无所不能的final关键字 不同于C#的Java值类型和String类型
记录几个Json的lib
Bryan Wong · 2013-02-15 · via 博客园 - Bryan Wong

1, jettison

jettison可以转换json和xml格式,并通过这种途径来将json字符串解析成Java对象。其采用STAX的方式进行json转换,用法如下

public class Parse
{
	/**
	 * @param args
	 * @throws JSONException 
	 */
	public static void main(String[] args) throws JSONException
	{
		JSONObject userString = new JSONObject("{\"jaxb\":{\"name\" : \"abc\"}}");

		AbstractXMLStreamReader reader = null;
        try
        {
	        reader = new MappedXMLStreamReader(userString);
	        
	        try
            {
	            JAXBContext jc = JAXBContext.newInstance(Jaxb.class);
	            
	            Unmarshaller unmarshaller = jc.createUnmarshaller();
	            
	            Object jaxb = unmarshaller.unmarshal(reader);
	            
	            System.out.println(jaxb);
	            
	            StringWriter sw = new StringWriter();
	            MappedNamespaceConvention con = new MappedNamespaceConvention(new Configuration());
	            XMLStreamWriter xsw = new MappedXMLStreamWriter(con, sw);
	            
	            Marshaller marshaller = jc.createMarshaller();
	            marshaller.marshal(jaxb, xsw);
	            
	            System.out.println(sw.toString());
	            try
                {
	                sw.close();
                } catch (IOException e)
                {
	                e.printStackTrace();
                }
	            
            } catch (JAXBException e)
            {
	            e.printStackTrace();
            }
        } catch (XMLStreamException e1)
        {
	        e1.printStackTrace();
        }
		
        if (reader != null)
        {
			try
            {
                reader.close();
            } catch (XMLStreamException e)
            {
                e.printStackTrace();
            }
        }
	}

}

2,jackson

jackson可以提供灵活的转换策略,例如是否在转换中将根属性识别为对象类型(jettison会,json-lib不会,jackson默认不会,根据选项判断),在遇到不能识别的属性时是否抛出异常(jettison不会,json-lib不会,jackson默认会,可根据选项判断)等

public class DataBindingParser
{

	/**
	 * @param args
	 */
	@SuppressWarnings("unchecked")
    public static void main(String[] args)
	{
		String userString = "{\"User\":{\"name\" : { \"first\" : \"Joe\", \"last\" : \"Sixpack\" },\"gender\" : \"MALE\", \"verified\" : false, \"userImage\" : \"Rm9vYmFyIQ==\"}}";
		String userStringEx = "{\"name\" : { \"first\" : \"Joe\", \"last\" : \"Sixpack\" },\"gender\" : \"MALE\", \"age\" : 18, \"verified\" : false, \"userImage\" : \"Rm9vYmFyIQ==\"}";
		
		ObjectMapper mapper = new ObjectMapper(); 
		
		try
		{
			mapper.enable(DeserializationFeature.UNWRAP_ROOT_VALUE);
			mapper.enable(SerializationFeature.WRAP_ROOT_VALUE);
			User user = mapper.readValue(userString, User.class);
			System.out.println("userString-->" + user);
			System.out.println("userString<--" + mapper.writeValueAsString(user));
			
			mapper.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES);
			mapper.disable(DeserializationFeature.UNWRAP_ROOT_VALUE);
			User userEx = mapper.readValue(userStringEx, User.class);
			System.out.println("userStringEx-->" + userEx);
			System.out.println("userStringEx<--" + mapper.writeValueAsString(userEx));
			System.out.println("=========================");
			
            Map<String,Object> userData = mapper.readValue(userString, Map.class);
			System.out.println("userString-->" + userData);
			System.out.println("userString<--" + mapper.writeValueAsString(userData));
			
            Map<String,Object> userDataEx = mapper.readValue(userStringEx, Map.class);
			System.out.println("userStringEx-->" + userDataEx);
			System.out.println("userStringEx<--" + mapper.writeValueAsString(userDataEx));
			
		} catch (JsonParseException e)
		{
			e.printStackTrace();
		} catch (JsonMappingException e)
		{
			e.printStackTrace();
		} catch (IOException e)
		{
			e.printStackTrace();
		}
	}

}