fastjson处理json实例

版本:

fastjson-1.1.28.jar

commons-lang-2.4.jar

概述:

fastjson为一款JSON 解析器和同时支持序列化操作,性能很高。

使用demo:

public class JsonVo {
	public JsonVo() {
		super();
	}

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

	private String id;
	private String tid;
	private String name;
	private Set<String> set;

	public String getId() {
		return id;
	}

	public Set<String> getSet() {
    	return set;
    }

	public void setSet(Set<String> set) {
    	this.set = set;
    }

	public String getTid() {
		return tid;
	}

	public void setTid(String tid) {
		this.tid = tid;
	}

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

	public String getName() {
		return name;
	}

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

	@Override
    public String toString() {
	    return "Tmp [id=" + id + ", name=" + name + ", set=" + set + ", tid=" + tid + "]";
    }
}

 使用:

JsonVo tmp = new JsonVo("id1", "name1");

String json = JSON.toJSONString(tmp);

System.out.println(json);
String jsonStr = "{\"id\":\"id1\",\"name\":\"name1\"}";
JSONObject jsonObject = JSONObject.parseObject(jsonStr);
System.out.println("->" + JSONObject.toJavaObject(jsonObject, Map.class));
System.out.println(JSON.toJavaObject(JSON.parseObject(jsonStr), JsonVo.class));
System.out.println(Boolean.valueOf(null));
Map<String, Float> map = new HashMap<String, Float>();
for (int i = 0; i < 100; i++) {
	String key = RandomStringUtils.random(3, "abcd");
	float value = RandomUtils.nextFloat();
	map.put(key, value);
}
System.out.println(map);
Map<String, Float> last = JSON.toJavaObject(JSONObject.parseObject(JSON.toJSONString(map)),
	Map.class);
Set<Entry<String, Float>> set = last.entrySet();

Iterator<Entry<String, Float>> entryIterator = last.entrySet().iterator();
while (entryIterator.hasNext()) {
	Entry<String, Float> entry = entryIterator.next();
	System.out.println(entry.getKey());
	System.out.println(entry.getValue());
}
System.out.println(last);
Set<String> hashSet = new HashSet<String>();
for (int i = 0; i < 100; i++) {
	String key = RandomStringUtils.random(3, "abcd");
	hashSet.add(key);
}
tmp.setSet(hashSet);

json = JSON.toJSONString(tmp);
System.out.println(json);

JsonVo tm = JSON.parseObject(json, JsonVo.class);
System.out.println(tm);
tm = JSON.parseObject(JSON.toJSONBytes(tm), JsonVo.class);

System.out.println("=>" + tm);
System.out.println("=>" + JSON.toJSONString(JSON.toJSONBytes(tm)));

 对于List<T>处理

List<T> list=JSON.parseArray(String text, T.class)

 对于Map<String,T>处理

Map<String, T> userMap = JSON.parseObject(text, new TypeReference<Map<String, T>>() {
			@Override
            public Type getType() {
	            return super.getType();
            }
			
});

猜你喜欢

转载自snv.iteye.com/blog/1860671