JsonTools是一个不错的JSON序列化和反序列化功能包,在这里可以下载到它:http://jsontools.berlios.de/。
它有以下功能:
- Parser: Parse JSON text files and convert these to a Java model.
- Renderer: Render a Java representation into text.
- 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, ...) .
- 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.
- 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());
}
}