Java利用json-tool操作json和java对象转换

需要json-tool的jar
package com.bryant.json;

import java.io.StringReader;

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

public class TestJsonTools
{
	public static void main(String[] args)
	{
		JsonModel model1 = new JsonModel(1, "bryant");
		String json = toJson(model1, true);
		System.out.println(json);
		JsonModel model2 = toModel(json, JsonModel.class);
		System.out.println(model2);
	}
	
	static <T> String toJson(T t, boolean format)
	{
		String result = null;
		try
		{
			result = JSONMapper.toJSON(t).render(format);
		}
		catch (MapperException e)
		{
			e.printStackTrace();
		}
		return result;
	}
	
	static <T> T toModel(String json, Class<T> clazz)
	{
		T t = null;
		JSONParser parser = new JSONParser(new StringReader(json));
		try
		{
			t = (T)JSONMapper.toJava(parser.nextValue(), clazz);
		}
		catch (Exception e)
		{
			e.printStackTrace();
		}
		return t;
	}
}
public class JsonModel
{
	@Override
	public String toString()
	{
		return "JsonModel [id=" + id + ", name=" + name + "]";
	}

	private int id;
	
	private String name;

	public int getId()
	{
		return id;
	}

	public JsonModel()
	{
		super();
	}

	public JsonModel(int id, String name)
	{
		super();
		this.id = id;
		this.name = name;
	}

	public void setId(int id)
	{
		this.id = id;
	}

	public String getName()
	{
		return name;
	}

	public void setName(String name)
	{
		this.name = name;
	}
}


你可能感兴趣的:(java,json)