`

JSON的序列化和反序列化

    博客分类:
  • Java
阅读更多

    JsonTools是一个不错的JSON序列化和反序列化功能包,在这里可以下载到它:http://jsontools.berlios.de/

 

    它有以下功能:

  1. Parser: Parse JSON text files and convert these to a Java model.
  2. Renderer: Render a Java representation into text.
  3. Serializer: Serialize plain POJO clusters to a JSON representation. The goal is to provide a serializing mechanism which can cope with all kinds of Java datastructures (recursion, references, primitive types, ...) .
  4. Mapper: Map POJO to JSON, this time the JSON text should be as clean as possible. This tool is the best choice when data has to be communicated between Java and other programming languages who can parse JSON.
  5. Validator: Validate the contents of a JSON file using a JSON schema.

    如何使用呢?请参考下面我写的示例代码:

package test;

import java.io.StringReader;

import test.vo.ClientTicketOrder;
import test.vo.TicketItem;
import antlr.RecognitionException;
import antlr.TokenStreamException;

import com.sdicons.json.mapper.JSONMapper;
import com.sdicons.json.mapper.MapperException;
import com.sdicons.json.model.JSONValue;
import com.sdicons.json.parser.JSONParser;

public class TestJsonTools {

	/**
	 * @param args
	 * @throws MapperException 
	 * @throws RecognitionException 
	 * @throws TokenStreamException 
	 */
	public static void main(String[] args) throws MapperException, TokenStreamException, RecognitionException {
		
		ClientTicketOrder order = new ClientTicketOrder();
		order.setClientOrderNo("0812333"); 
    	
		TicketItem tItem = new TicketItem();
		tItem.setPnr("UY8YG");
		
		order.setTicketItems(new TicketItem[]{tItem});    	
    	
    	//JavaBean to JSON
		JSONValue jsonValue = JSONMapper.toJSON( order );
		String jsonStr = jsonValue.render(false);
		System.out.println(jsonStr);

		//JSON to JavaBean
		JSONParser parser = new JSONParser(new StringReader(jsonStr));
		ClientTicketOrder u = (ClientTicketOrder) JSONMapper.toJava(parser.nextValue(), ClientTicketOrder.class);
		System.out.println(u.getClientOrderNo() + " " + u.getTicketItems()[0].getPnr());
		
	}

}

 

  • jsontools-core-1.6.jar (138.1 KB)
  • 描述: 目前最新版是1.6,注意它要依赖antlr-2.7.6.jar!
  • 下载次数: 177
分享到:
评论
2 楼 liuweihug 2014-08-01  
json序列化反序列化插件-json2.js 介绍和使用 - 前端编程 - IT工作生活这点事。Just Such So!
http://www.suchso.com/UIweb/json2-js-stringify-parse-serializable-deserialize.html
1 楼 sunyujia 2008-08-16  
看上去不错

相关推荐

Global site tag (gtag.js) - Google Analytics