(转)java bean、List、数组、map和Json的相互转化

java bean、List、数组、map和Json的相互转化

 

工程

 json包为 

代码

package com.my.json;


public class ChildBean {

    private String childName;

    private String childSex;

    private int childAge;

    public ChildBean()
    {
        
    }
    public ChildBean(String childName, String childSex, int childAge) {
        this.childName = childName;
        this.childSex = childSex;
        this.childAge = childAge;
    }

     
    public String getChildName() {
        return childName;
    }


    public void setChildName(String childName) {
        this.childName = childName;
    }


    public String getChildSex() {
        return childSex;
    }


    public void setChildSex(String childSex) {
        this.childSex = childSex;
    }


    public int getChildAge() {
        return childAge;
    }


    public void setChildAge(int childAge) {
        this.childAge = childAge;
    }


    @Override
    public String toString() {
        return "ChildBean [childName=" + childName + ", childSex=" + childSex + ", childAge=" + childAge + "]";
    }

}
package com.my.json;

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

public class Person {

    private String name;

    private List<ChildBean> list = new ArrayList<ChildBean>();

    private int num;

    private String sex;

    private int age;

    public Person() {

    }

    public Person(String name, int num, String sex, int age) {
        super();
        this.name = name;
        this.num = num;
        this.sex = sex;
        this.age = age;
    }

    public int getAge() {
        return age;
    }

    public String getName() {
        return name;
    }

    public int getNum() {
        return num;
    }

    public String getSex() {
        return sex;
    }

    public void setAge(int age) {
        this.age = age;
    }

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

    public void setNum(int num) {
        this.num = num;
    }

    public void setSex(String sex) {
        this.sex = sex;
    }

    public List<ChildBean> getList() {
        return list;
    }

    public void setList(List<ChildBean> list) {
        this.list = list;
    }

    @Override
    public String toString() {
        return "Person [name=" + name + ", num=" + num + ", sex=" + sex + ", age=" + age + ",list=" + list + "]";
    }

}
package com.my.json;

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

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import net.sf.json.JSONSerializer;
import net.sf.json.JsonConfig;

public class JsonUtil {

    /**
     * 简单类型:Json转化为bean
     * 
     * @param jsonString
     * @param pojoCalss
     * @return
     */
    public static Object jsonString2Object(String jsonString, Class pojoCalss) {

        JSONObject jsonObject = JSONObject.fromObject(jsonString);

        Object pojo = JSONObject.toBean(jsonObject, pojoCalss);

        return pojo;

    }

    /**
     * 复杂类型:Json转化为bean<br>
     * 用法示例:<br>
     * Map<String, Class> classMap = new HashMap<String, Class>();
     * classMap.put("list", ChildBean.class); //指定复杂类型属性的映射关系,可以使多个放到map中<br>
     * Person person=(Person)JsonUtil.jsonString2Object(str2, Person.class,
     * classMap);<br>
     * 
     * @param jsonString
     * @param pojoCalss
     * @return
     */
    public static Object jsonString2Object(String jsonString, Class pojoCalss, Map<String, Class> classMap) {
        JSONObject jobj = JSONObject.fromObject(jsonString);
        return JSONObject.toBean(jobj, pojoCalss, classMap);
    }

    /**
     * 简单|复杂类型:将java对象转换成json字符串<br>
     * 支持复杂类型:Java bean 中既有属性又有list
     * 
     * @param javaObj
     * @return
     */
    public static String object2JsonString(Object javaObj) {

        JSONObject json = JSONObject.fromObject(javaObj);

        return json.toString();

    }

    /**
     * 从json对象集合表达式中得到一个java对象列表
     * 
     * @param jsonString
     * @param pojoClass
     * @return
     */
    public static List jsonList2JavaList(String jsonString, Class pojoClass) {

        JSONArray jsonArray = JSONArray.fromObject(jsonString);

        JSONObject jsonObject;

        Object pojoValue;

        List list = new ArrayList();

        for (int i = 0; i < jsonArray.size(); i++) {

            jsonObject = jsonArray.getJSONObject(i);

            pojoValue = JSONObject.toBean(jsonObject, pojoClass);

            list.add(pojoValue);

        }

        return list;

    }

    /**
     * 从java对象集合表达式中得到一个json列表
     * 
     * @param list
     * @return
     */
    public static String javaList2JsonList(List list) {

        JSONArray jsonArray = JSONArray.fromObject(list);
        return jsonArray.toString();
    }

    /**
     * 数组转换为JSON
     * 
     * @param array
     * @return
     */
    public static String javaArray2Json(Object[] array) {
        JSONArray jsonarray = JSONArray.fromObject(array);
        return jsonarray.toString();
    }

    /**
     * Json数组转化为Java数组
     * 
     * @param jsonArray
     * @param clas
     * @return
     */
    public static Object jsonArray2JavaArrray(String jsonArray, Class clas) {
        JsonConfig jconfig = new JsonConfig();
        jconfig.setArrayMode(JsonConfig.MODE_OBJECT_ARRAY);
        jconfig.setRootClass(clas);
        JSONArray jarr = JSONArray.fromObject(jsonArray);
        return JSONSerializer.toJava(jarr, jconfig);
    }

    /**
     * Map转换成json
     * @param map
     * @return
     */
    public static String javaMap2Json(Map<String, Object> map) {
        return JSONObject.fromObject(map).toString();
    }
    
    /**
     * json转化为map
     * @param jsonString
     * @param pojoCalss
     * @return
     */
    public static Object javaMap2Json(String jsonString, Class pojoCalss) {
        return jsonString2Object(jsonString, pojoCalss);//调用方法jsonString2Object
    }

}

复制代码
复制代码

package com.my.json;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class Test {
    @SuppressWarnings("unchecked")
    public static void main(String[] args) {

        // 普通bean转化Json
        System.out.println("普通bean转化Json:");
        ChildBean p = new ChildBean("wwwww", "boy", 23);
        String str = JsonUtil.object2JsonString(p);
        System.out.println(str);

        // 普通Json转化bean,如 {"childAge":23,"childName":"wwwww","childSex":"boy"}
        System.out.println("普通Json转化bean:");
        ChildBean c = (ChildBean) JsonUtil.jsonString2Object(str, ChildBean.class);
        System.out.println(c);

        // Java List转化为Json
        System.out.println("Java List转化为Json:");
        List<ChildBean> list = new ArrayList<ChildBean>();
        for (int i = 0; i < 5; i++) {
            ChildBean childBean = new ChildBean("wwwww" + i, "boy", i);
            list.add(childBean);
        }
        String jsonList = JsonUtil.javaList2JsonList(list);
        System.out.println(jsonList);

        // json 列表转化为Java List
        System.out.println("json 列表转化为Java List:");
        List<ChildBean> l = (List<ChildBean>) JsonUtil.jsonList2JavaList(jsonList, ChildBean.class);
        System.out.println(l);

        // 复杂bean转化为Json
        System.out.println("复杂bean转化为Json:");
        List<ChildBean> list2 = new ArrayList<ChildBean>();
        for (int i = 0; i < 10; i++) {
            ChildBean childBean = new ChildBean("aaaaaa" + i, "boy", i);
            list2.add(childBean);
        }
        Person me = new Person("zhang", 1, "man", 1);
        me.setList(list2);

        String str2 = JsonUtil.object2JsonString(me);
        System.out.println("str2=" + str2);

        // 复杂Json转化bean
        System.out.println("复杂Json转化bean:");
        Map<String, Class> classMap = new HashMap<String, Class>();
        classMap.put("list", ChildBean.class); // 指定复杂类型属性的映射关系,可以使多个放到map中
        Person person = (Person) JsonUtil.jsonString2Object(str2, Person.class, classMap);
        System.out.println(person);
        System.out.println(person.getList().get(0).getChildName());

        // Java数组转换为JSON
        System.out.println("java数组转换为JSON:");
        // String[] array = {"asd","dfgd","asd","234"};
        ChildBean[] array = new ChildBean[10];
        for (int i = 0; i < 10; i++) {
            ChildBean childBean = new ChildBean("aaaaaa" + i, "boy", i);
            array[i] = childBean;
        }
        String jsonArray = JsonUtil.javaArray2Json(array);
        System.out.println(jsonArray);

        // Json数组转化为Java数组
        System.out.println("Json数组转化为Java数组:");
        ChildBean[] cb = (ChildBean[]) JsonUtil.jsonArray2JavaArrray(jsonArray, ChildBean.class);
        System.out.println(Arrays.toString(cb));

        //Map转换成json
        System.out.println("Map转换成json:");
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("userId", 1000);
        map.put("userName", "张三");
        map.put("userSex", "男");
        String jsonStr = JsonUtil.javaMap2Json(map);
        System.out.println(jsonStr);
        
        //json转化为map
        System.out.println("json转化为map:");
        Map<String, Object> jmap = (Map<String, Object>)JsonUtil.javaMap2Json(jsonStr, Map.class);
        System.out.println(jmap);
    }
}

注意:

1.代转化的bean如果自定义了构造方法,必须写上默认的构造方法,否则Json转化时候,曝出init()方法找不到!

2.对于Date和Timestamp日期类型字段需要单独处理(本例不含这种类型,请参看我的博客《含有Date和Timestamp的Java和Json互相转化》)

posted @ 2017-02-22 16:06  烟雨观春柳  阅读(502)  评论(0编辑  收藏  举报