java数据类型转换____FastJson框架对象和JSON转换

package com.cnse.convert.fastjson;

import java.util.ArrayList;
import java.util.List;

import com.alibaba.fastjson.JSON;
import com.cnse.convert.gson.User;

/**
 * @author Administrator
 * fastjson开发包
 */
public class FastJsonUtil {
	/**
	 * fastJson单个对象间转换========================================
	 * @param obj
	 * @return
	 */
	public static String objToJson(Object obj){
		return JSON.toJSONString(obj);
	}
	public static Object jsonToObj(Class<?> clazz,String jsonStr){
		return JSON.parseObject(jsonStr, clazz);
	}
	/**
	 * fastJson多个对象间转换==========================================
	 * @param obj
	 * @return
	 */
	public static String objSToJson(Object obj){
		return JSON.toJSONString(obj);
	}
	
	public static void main(String[] args) {
		//初始化对象
		User u1 = new User();
			u1.setUserid(1);
			u1.setUsername("zhangsan");
			u1.setPassword("123456");
		User u2 = new User();
			u2.setUserid(2);
			u2.setUsername("lisi");
			u2.setPassword("8888");
		// 初始化Gson对象
		List<User>list=new ArrayList<User>();
			list.add(u1);
			list.add(u2);
		//===================单个对象间转换====================
		System.out.println("FastJson对象转Json串___:"+objToJson(u1));
		User user=(User) jsonToObj(User.class,objToJson(u1));
		System.out.println("FastJson的json串转对象___"+u2.getUsername());
		//===================多个对象间转换====================	
		String jsonStrS=objSToJson(list);
		System.out.println("多个user转成json串__:"+objSToJson(list));
		List<User> userlist = JSON.parseArray(jsonStrS, User.class);
		System.out.println(userlist.get(0).getUsername());
	}
}

//运行结果


posted @ 2017-02-26 18:40  蜜獾互联网  阅读(2)  评论(0编辑  收藏  举报  来源