JSON的序列化和反序列化

    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());
		
	}

}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值