jsonUtil

JsonUtil:

package com.bxw.demo;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import net.sf.ezmorph.MorpherRegistry;
import net.sf.ezmorph.object.DateMorpher;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import net.sf.json.JsonConfig;
import net.sf.json.processors.JsonValueProcessor;
import net.sf.json.util.JSONUtils;
import net.sf.json.xml.XMLSerializer;

public class JsonUtil {     

    /**
     * 设置日期转换格式
     */
    static {
        //注册器
        MorpherRegistry mr = JSONUtils.getMorpherRegistry();     

        //可转换的日期格式,即Json串中可以出现以下格式的日期与时间
        DateMorpher dm = new DateMorpher(new String[] { Util.YYYY_MM_DD,
                Util.YYYY_MM_DD_HH_MM_ss, Util.HH_MM_ss, Util.YYYYMMDD,
                Util.YYYYMMDDHHMMSS, Util.HHMMss });
        mr.registerMorpher(dm);
    }     

    /**
    * 从json串转换成实体对象
    * @param jsonObjStr e.g. {‘name‘:‘get‘,‘dateAttr‘:‘2009-11-12‘}
    * @param clazz Person.class
    * @return
    */
    public static Object getDtoFromJsonObjStr(String jsonObjStr, Class clazz) {
        return JSONObject.toBean(JSONObject.fromObject(jsonObjStr), clazz);
    }     

    /**
    * 从json串转换成实体对象,并且实体集合属性存有另外实体Bean
    * @param jsonObjStr e.g. {‘data‘:[{‘name‘:‘get‘},{‘name‘:‘set‘}]}
    * @param clazz e.g. MyBean.class
    * @param classMap e.g. classMap.put("data", Person.class)
    * @return Object
    */
    public static Object getDtoFromJsonObjStr(String jsonObjStr, Class clazz, Map classMap) {
        return JSONObject.toBean(JSONObject.fromObject(jsonObjStr), clazz, classMap);
    }     

    /**
    * 把一个json数组串转换成普通数组
    * @param jsonArrStr  e.g. [‘get‘,1,true,null]
    * @return Object[]
    */
    public static Object[] getArrFromJsonArrStr(String jsonArrStr) {
        return JSONArray.fromObject(jsonArrStr).toArray();
    }     

    /**
    * 把一个json数组串转换成实体数组
    * @param jsonArrStr e.g. [{‘name‘:‘get‘},{‘name‘:‘set‘}]
    * @param clazz e.g. Person.class
    * @return Object[]
    */
    public static Object[] getDtoArrFromJsonArrStr(String jsonArrStr, Class clazz) {
        JSONArray jsonArr = JSONArray.fromObject(jsonArrStr);
        Object[] objArr = new Object[jsonArr.size()];
        for (int i = 0; i < jsonArr.size(); i++) {
            objArr[i] = JSONObject.toBean(jsonArr.getJSONObject(i), clazz);
        }
        return objArr;
    }     

    /**
    * 把一个json数组串转换成实体数组,且数组元素的属性含有另外实例Bean
    * @param jsonArrStr e.g. [{‘data‘:[{‘name‘:‘get‘}]},{‘data‘:[{‘name‘:‘set‘}]}]
    * @param clazz e.g. MyBean.class
    * @param classMap e.g. classMap.put("data", Person.class)
    * @return Object[]
    */
    public static Object[] getDtoArrFromJsonArrStr(String jsonArrStr, Class clazz,
            Map classMap) {
        JSONArray array = JSONArray.fromObject(jsonArrStr);
        Object[] obj = new Object[array.size()];
        for (int i = 0; i < array.size(); i++) {
            JSONObject jsonObject = array.getJSONObject(i);
            obj[i] = JSONObject.toBean(jsonObject, clazz, classMap);
        }
        return obj;
    }     

    /**
    * 把一个json数组串转换成存放普通类型元素的集合
    * @param jsonArrStr  e.g. [‘get‘,1,true,null]
    * @return List
    */
    public static List getListFromJsonArrStr(String jsonArrStr) {
        JSONArray jsonArr = JSONArray.fromObject(jsonArrStr);
        List list = new ArrayList();
        for (int i = 0; i < jsonArr.size(); i++) {
            list.add(jsonArr.get(i));
        }
        return list;
    }     

    /**
    * 把一个json数组串转换成集合,且集合里存放的为实例Bean
    * @param jsonArrStr e.g. [{‘name‘:‘get‘},{‘name‘:‘set‘}]
    * @param clazz
    * @return List
    */
    public static List getListFromJsonArrStr(String jsonArrStr, Class clazz) {
        JSONArray jsonArr = JSONArray.fromObject(jsonArrStr);
        List list = new ArrayList();
        for (int i = 0; i < jsonArr.size(); i++) {
            list.add(JSONObject.toBean(jsonArr.getJSONObject(i), clazz));
        }
        return list;
    }     

    /**
    * 把一个json数组串转换成集合,且集合里的对象的属性含有另外实例Bean
    * @param jsonArrStr e.g. [{‘data‘:[{‘name‘:‘get‘}]},{‘data‘:[{‘name‘:‘set‘}]}]
    * @param clazz e.g. MyBean.class
    * @param classMap e.g. classMap.put("data", Person.class)
    * @return List
    */
    public static List getListFromJsonArrStr(String jsonArrStr, Class clazz, Map classMap) {
        JSONArray jsonArr = JSONArray.fromObject(jsonArrStr);
        List list = new ArrayList();
        for (int i = 0; i < jsonArr.size(); i++) {
            list.add(JSONObject.toBean(jsonArr.getJSONObject(i), clazz, classMap));
        }
        return list;
    }     

    /**
    * 把json对象串转换成map对象
    * @param jsonObjStr e.g. {‘name‘:‘get‘,‘int‘:1,‘double‘,1.1,‘null‘:null}
    * @return Map
    */
    public static Map getMapFromJsonObjStr(String jsonObjStr) {
        JSONObject jsonObject = JSONObject.fromObject(jsonObjStr);     

        Map map = new HashMap();
        for (Iterator iter = jsonObject.keys(); iter.hasNext();) {
            String key = (String) iter.next();
            map.put(key, jsonObject.get(key));
        }
        return map;
    }     

    /**
    * 把json对象串转换成map对象,且map对象里存放的为其他实体Bean
    * @param jsonObjStr e.g. {‘data1‘:{‘name‘:‘get‘},‘data2‘:{‘name‘:‘set‘}}
    * @param clazz e.g. Person.class
    * @return Map
    */
    public static Map getMapFromJsonObjStr(String jsonObjStr, Class clazz) {
        JSONObject jsonObject = JSONObject.fromObject(jsonObjStr);     

        Map map = new HashMap();
        for (Iterator iter = jsonObject.keys(); iter.hasNext();) {
            String key = (String) iter.next();
            map.put(key, JSONObject.toBean(jsonObject.getJSONObject(key), clazz));
        }
        return map;
    }     

    /**
     * 把json对象串转换成map对象,且map对象里存放的其他实体Bean还含有另外实体Bean
     * @param jsonObjStr e.g. {‘mybean‘:{‘data‘:[{‘name‘:‘get‘}]}}
     * @param clazz e.g. MyBean.class
     * @param classMap  e.g. classMap.put("data", Person.class)
     * @return Map
     */
    public static Map getMapFromJsonObjStr(String jsonObjStr, Class clazz, Map classMap) {
        JSONObject jsonObject = JSONObject.fromObject(jsonObjStr);     

        Map map = new HashMap();
        for (Iterator iter = jsonObject.keys(); iter.hasNext();) {
            String key = (String) iter.next();
            map.put(key, JSONObject
                    .toBean(jsonObject.getJSONObject(key), clazz, classMap));
        }
        return map;
    }     

    /**
     * 把实体Bean、Map对象、数组、列表集合转换成Json串
     * @param obj
     * @return
     * @throws Exception String
     */
    public static String getJsonStr(Object obj) {
        String jsonStr = null;
        //Json配置
        JsonConfig jsonCfg = new JsonConfig();     

        //注册日期处理器
        jsonCfg.registerJsonValueProcessor(java.util.Date.class,
                new JsonDateValueProcessor(Util.YYYY_MM_DD_HH_MM_ss));
        if (obj == null) {
            return "{}";
        }     

        if (obj instanceof Collection || obj instanceof Object[]) {
            jsonStr = JSONArray.fromObject(obj, jsonCfg).toString();
        } else {
            jsonStr = JSONObject.fromObject(obj, jsonCfg).toString();
        }     

        return jsonStr;
    }     

    /**
     * 把json串、数组、集合(collection map)、实体Bean转换成XML
     * XMLSerializer API:
     * http://json-lib.sourceforge.net/apidocs/net/sf/json/xml/XMLSerializer.html
     * 具体实例请参考:
     * http://json-lib.sourceforge.net/xref-test/net/sf/json/xml/TestXMLSerializer_writes.html
     * http://json-lib.sourceforge.net/xref-test/net/sf/json/xml/TestXMLSerializer_writes.html
     * @param obj
     * @return
     * @throws Exception String
     */
    public static String getXMLFromObj(Object obj) {
        XMLSerializer xmlSerial = new XMLSerializer();     

        //Json配置
        JsonConfig jsonCfg = new JsonConfig();     

        //注册日期处理器
        jsonCfg.registerJsonValueProcessor(java.util.Date.class,
                new JsonDateValueProcessor(Util.YYYY_MM_DD_HH_MM_ss));     

        if ((String.class.isInstance(obj) && String.valueOf(obj).startsWith("["))
                || obj.getClass().isArray() || Collection.class.isInstance(obj)) {
            JSONArray jsonArr = JSONArray.fromObject(obj, jsonCfg);
            return xmlSerial.write(jsonArr);
        } else {
            JSONObject jsonObj = JSONObject.fromObject(obj, jsonCfg);
            return xmlSerial.write(jsonObj);
        }
    }     

    /**
     * 从XML转json串
     * @param xml
     * @return String
     */
    public static String getJsonStrFromXML(String xml) {
        XMLSerializer xmlSerial = new XMLSerializer();
        return String.valueOf(xmlSerial.read(xml));
    }     

}     

/**
 * json日期值处理器实现
 * (C) 2009-9-11, jzj
 */
class JsonDateValueProcessor implements JsonValueProcessor {     

    private String format = Util.YYYY_MM_DD_HH_MM_ss;     

    public JsonDateValueProcessor() {     

    }     

    public JsonDateValueProcessor(String format) {
        this.format = format;
    }     

    public Object processArrayValue(Object value, JsonConfig jsonConfig) {
        return process(value, jsonConfig);
    }     

    public Object processObjectValue(String key, Object value, JsonConfig jsonConfig) {
        return process(value, jsonConfig);
    }     

    private Object process(Object value, JsonConfig jsonConfig) {
        if (value instanceof Date) {
            String str = new SimpleDateFormat(format).format((Date) value);
            return str;
        }
        return value == null ? null : value.toString();
    }     

    public String getFormat() {
        return format;
    }     

    public void setFormat(String format) {
        this.format = format;
    }     

}    

JsonUtilTest:

package com.bxw.demo;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;     

import com.bxw.entity.MyBean;
import com.bxw.entity.Person;

import junit.framework.TestCase;     

/**
 * JsonUtil测试类
 * (C) 2009-9-11, jzj
 */
public class JsonUtilTest extends TestCase {     

    /**
     * 从json串转换成实体对象,且实体中Date属性能正确转换
     *  void
     */
    public void testGetDtoFromJsonObjStr1() {
        String json = "{‘name‘:‘get‘,‘dateAttr‘:‘2009-11-12‘}";
        Person ps = (Person) JsonUtil.getDtoFromJsonObjStr(json, Person.class);
        //print: get
        System.out.println(ps.getName());
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        //print: 2009-11-12
        System.out.println(sdf.format(ps.getDateAttr()));
    }     

    /**
     * 从json串转换成实体对象,并且实体集合属性存有另外实体Bean
     *  void
     */
    public void testGetDtoFromJsonObjStr3() {
        String json = "{‘data‘:[{‘name‘:‘get‘},{‘name‘:‘set‘}]}";
        Map classMap = new HashMap();
        classMap.put("data", Person.class);
        MyBean myBean = (MyBean) JsonUtil.getDtoFromJsonObjStr(json, MyBean.class,
                classMap);
        //print: class comm.test.Person name =get
        System.out.println(myBean.getData().get(0).getClass() + " name ="
                + ((Person) myBean.getData().get(0)).getName());
        //print: class comm.test.Person name =set
        System.out.println(myBean.getData().get(1).getClass() + " name ="
                + ((Person) myBean.getData().get(1)).getName());
    }     

    /**
     * 把一个json数组串转换成普通数组
     *  void
     */
    public void testGetArrFromJsonArrStr() {
        String json = "[‘get‘,1,true,null]";
        Object[] objArr = JsonUtil.getArrFromJsonArrStr(json);
        for (int i = 0; i < objArr.length; i++) {
            System.out.println(objArr[i].getClass() + " " + objArr[i]);
        }
        /*  print:
            class java.lang.String get
            class java.lang.Integer 1
            class java.lang.Boolean true
            class net.sf.json.JSONNull null
         */
    }     

    /**
     * 把一个json数组串转换成实体数组
     *  void
     */
    public void testGetDtoArrFromJsonArrStr1() {
        String json = "[{‘name‘:‘get‘},{‘name‘:‘set‘}]";
        Object[] objArr = JsonUtil.getDtoArrFromJsonArrStr(json, Person.class);
        for (int i = 0; i < objArr.length; i++) {
            System.out.println(objArr[i].getClass() + " name = "
                    + ((Person) objArr[i]).getName());
        }
        /*  print:
            class comm.test.Person name = get
            class comm.test.Person name = set
         */
    }     

    /**
     * 把一个json数组串转换成实体数组,且数组元素的属性含有另外实例Bean
     *  void
     */
    public void testGetDtoArrFromJsonArrStr2() {
        String json = "[{‘data‘:[{‘name‘:‘get‘}]},{‘data‘:[{‘name‘:‘set‘}]}]";
        Map classMap = new HashMap();
        classMap.put("data", Person.class);
        Object[] objArr = JsonUtil.getDtoArrFromJsonArrStr(json, MyBean.class, classMap);
        for (int i = 0; i < objArr.length; i++) {
            System.out.println(((MyBean) objArr[i]).getData().get(0).getClass()
                    + " name = "
                    + ((Person) ((MyBean) objArr[i]).getData().get(0)).getName());
        }
        /*  print:
            class comm.test.Person name = get
            class comm.test.Person name = set
         */
    }     

    /**
     * 把一个json数组串转换成存放普通类型元素的集合
     *  void
     */
    public void testGetListFromJsonArrStr1() {
        String json = "[‘get‘,1,true,null]";
        List list = JsonUtil.getListFromJsonArrStr(json);
        for (int i = 0; i < list.size(); i++) {
            System.out.println(list.get(i).getClass() + " " + list.get(i));
        }
        /*  print:
            class java.lang.String get
            class java.lang.Integer 1
            class java.lang.Boolean true
            class net.sf.json.JSONNull null
         */
    }     

    /**
     * 把一个json数组串转换成集合,且集合里存放的为实例Bean
     *  void
     */
    public void testGetListFromJsonArrStr2() {
        String json = "[{‘name‘:‘get‘},{‘name‘:‘set‘}]";
        List list = JsonUtil.getListFromJsonArrStr(json, Person.class);
        for (int i = 0; i < list.size(); i++) {
            System.out.println(list.get(i).getClass() + " name = "
                    + ((Person) list.get(i)).getName());
        }
        /*  print:
            class comm.test.Person name = get
            class comm.test.Person name = set
         */
    }     

    /**
     * 把一个json数组串转换成集合,且集合里的对象的属性含有另外实例Bean
     *  void
     */
    public void testGetListFromJsonArrStr3() {
        String json = "[{‘data‘:[{‘name‘:‘get‘}]},{‘data‘:[{‘name‘:‘set‘}]}]";
        Map classMap = new HashMap();
        classMap.put("data", Person.class);
        List list = JsonUtil.getListFromJsonArrStr(json, MyBean.class, classMap);
        for (int i = 0; i < list.size(); i++) {
            System.out.println(((MyBean) list.get(i)).getData().get(0).getClass()
                    + " name = "
                    + ((Person) ((MyBean) list.get(i)).getData().get(0)).getName());
        }
        /*  print:
            class comm.test.Person name = get
            class comm.test.Person name = set
         */
    }     

    /**
     * 把json对象串转换成map对象
     *  void
     */
    public void testGetMapFromJsonObjStr() {
        String json = "{‘name‘:‘get‘,‘int‘:1,‘double‘:1.1,‘null‘:null}";
        Map map = JsonUtil.getMapFromJsonObjStr(json);
        for (Iterator iter = map.keySet().iterator(); iter.hasNext();) {
            System.out.println(map.get(iter.next()).getClass());
        }
        /*  print:
            class java.lang.Double
            class net.sf.json.JSONNull
            class java.lang.Integer
            class java.lang.String
         */
    }     

    /**
     * 把json对象串转换成map对象,且map对象里存放的为其他实体Bean
     *  void
     */
    public void testGetMapFromJsonObjStr2() {
        String json = "{‘data1‘:{‘name‘:‘get‘},‘data2‘:{‘name‘:‘set‘}}";
        Map map = JsonUtil.getMapFromJsonObjStr(json, Person.class);
        for (Iterator iter = map.keySet().iterator(); iter.hasNext();) {
            String key = (String) iter.next();
            System.out.println(map.get(key).getClass() + " name="
                    + ((Person) map.get(key)).getName());
        }
        /*  print:
            class comm.test.Person name=set
            class comm.test.Person name=get
         */
    }     

    /**
     * 把json对象串转换成map对象,且map对象里
     * 存放的其他实体Bean还含有另外实体Bean
     *  void
     */
    public void testGetMapFromJsonObjStr3() {
        String json = "{‘mybean‘:{‘data‘:[{‘name‘:‘get‘}]}}";
        Map classMap = new HashMap();
        classMap.put("data", Person.class);
        Map map = JsonUtil.getMapFromJsonObjStr(json, MyBean.class, classMap);
        for (Iterator iter = map.keySet().iterator(); iter.hasNext();) {
            String key = (String) iter.next();
            Object o = ((MyBean) map.get(key)).getData().get(0);
            System.out.println(o.getClass() + " name=" + ((Person) o).getName());
        }
        /*  print:
            class comm.test.Person name=get
         */
    }     

    /**
     * 实体Bean转json串
     *  void
     */
    public void testgetJsonStr1() {
        Person ps = new Person();
        ps.setDateAttr(new Date());
        ps.setName("get");
        MyBean myBean = new MyBean();
        List list = new ArrayList();
        list.add(ps);     

        myBean.setData(list);
        //print: {"data":[{"dateAttr":"2009-09-12 07:24:54","name":"get"}]}
        System.out.println(JsonUtil.getJsonStr(myBean));
    }     

    /**
     * map转json串
     *  void
     */
    public void testgetJsonStr2() {
        Person ps = new Person();
        ps.setDateAttr(new Date());
        ps.setName("get");
        Map map = new LinkedHashMap();
        map.put("person1", ps);     

        //print: {"person1":{"dateAttr":"2009-09-12 07:24:27","name":"get"}}
        System.out.println(JsonUtil.getJsonStr(map));
    }     

    /**
     * 数组转json串
     *  void
     */
    public void testgetJsonStr3() {
        Person ps = new Person();
        ps.setDateAttr(new Date());
        ps.setName("get");
        Person[] personArr = new Person[1];
        personArr[0] = ps;
        //print: [{"dateAttr":"2009-09-12 07:23:54","name":"get"}]
        System.out.println(JsonUtil.getJsonStr(personArr));
    }     

    /**
     * list转json串
     *  void
     */
    public void testgetJsonStr4() {
        Person ps = new Person();
        ps.setDateAttr(new Date());
        ps.setName("get");
        List list = new ArrayList();
        list.add(ps);     

        //print: [{"dateAttr":"2009-09-12 07:22:49","name":"get"}]
        System.out.println(JsonUtil.getJsonStr(list));
    }     

    /**
     * set转json串
     *  void
     */
    public void testgetJsonStr5() {
        Person ps = new Person();
        ps.setDateAttr(new Date());
        ps.setName("get");
        Set set = new LinkedHashSet();
        set.add(ps);     

        //print: [{"dateAttr":"2009-09-12 07:22:16","name":"get"}]
        System.out.println(JsonUtil.getJsonStr(set));
    }     

    /**
     * json对象串转XML
     *  void
     */
    public void testGetXMLFromObj1() {
        System.out.println(JsonUtil
                .getXMLFromObj("{\"name\":\"json\",\"bool\":true,\"int\":1}"));
        /*  print:
            <?xml version="1.0" encoding="UTF-8"?>
            <o>
                <bool type="boolean">true</bool>
                <int type="number">1</int>
                <name type="string">json</name>
            </o>
         */
    }     

    /**
     * json数组串转XML
     *  void
     */
    public void testGetXMLFromObj2() {
        System.out.println(JsonUtil.getXMLFromObj("[1,2,3]"));
        /*  print:
            <?xml version="1.0" encoding="UTF-8"?>
            <a>
                <e type="number">1</e>
                <e type="number">2</e>
                <e type="number">3</e>
            </a>
         */
    }     

    /**
     * java数组转XML
     *  void
     */
    public void testGetXMLFromObj3() {
        Person ps = new Person();
        ps.setDateAttr(new Date());
        ps.setName("get");
        Person[] personArr = new Person[2];
        personArr[0] = ps;     

        System.out.println(JsonUtil.getXMLFromObj(personArr));
        /*  print:
            <?xml version="1.0" encoding="UTF-8"?>
            <a>
                <e class="object">
                    <dateAttr type="string">2009-09-12 06:58:55</dateAttr>
                    <name type="string">get</name>
                </e>
            </a>
         */
    }     

    /**
     * list转XML
     *  void
     */
    public void testGetXMLFromObj4() {
        Person ps = new Person();
        ps.setDateAttr(new Date());
        ps.setName("get");
        List list = new ArrayList();
        list.add(ps);     

        System.out.println(JsonUtil.getXMLFromObj(list));
        /*  print:
            <?xml version="1.0" encoding="UTF-8"?>
            <a>
                <e class="object">
                    <dateAttr type="string">2009-09-12 07:02:31</dateAttr>
                    <name type="string">get</name>
                </e>
            </a>
         */
    }     

    /**
     * set转XML
     * void
     */
    public void testGetXMLFromObj5() {
        Person ps = new Person();
        ps.setDateAttr(new Date());
        ps.setName("get");
        Set set = new LinkedHashSet();
        set.add(ps);     

        System.out.println(JsonUtil.getXMLFromObj(set));
        /*  print:
            <?xml version="1.0" encoding="UTF-8"?>
            <a>
                <e class="object">
                    <dateAttr type="string">2009-09-12 07:04:38</dateAttr>
                    <name type="string">get</name>
                </e>
            </a>
         */
    }     

    /**
     * map转XML
     *  void
     */
    public void testGetXMLFromObj6() {
        Person ps = new Person();
        ps.setDateAttr(new Date());
        ps.setName("get");
        Map map = new HashMap();
        map.put("person1", ps);     

        System.out.println(JsonUtil.getXMLFromObj(map));
        /*  print:
            <?xml version="1.0" encoding="UTF-8"?>
            <o>
                <person1 class="object">
                    <dateAttr type="string">2009-09-12 07:08:35</dateAttr>
                    <name type="string">get</name>
                </person1>
            </o>
         */
    }     

    /**
     * 实体Bean转XML
     *  void
     */
    public void testGetXMLFromObj7() {
        Person ps = new Person();
        ps.setDateAttr(new Date());
        ps.setName("get");
        System.out.println(JsonUtil.getXMLFromObj(ps));
        /*  print:
            <?xml version="1.0" encoding="UTF-8"?>
            <o>
                <dateAttr type="string">2009-09-12 07:13:02</dateAttr>
                <name type="string">get</name>
            </o>
         */
    }     

    /**
     * 从XML对象串转json串
     *  void
     */
    public void testGetJsonStrFromXML1() {
        String xml = "<o><dateAttr type=‘string‘>2009-09-12 07:13:02</dateAttr>"
                + "<name type=‘string‘>get</name></o>";
        //print: {"dateAttr":"2009-09-12 07:13:02","name":"get"}
        System.out.println(JsonUtil.getJsonStrFromXML(xml));
    }     

    /**
     * 从XML数组串转json串
     *  void
     */
    public void testGetJsonStrFromXML2() {
        String xml = "<a class=‘array‘><e class=‘object‘><dateAttr type=‘string‘>2009-09-12 07:04:38</dateAttr>"
                + "<name type=‘string‘>get</name></e></a>";
        //print: [{"dateAttr":"2009-09-12 07:04:38","name":"get"}]
        System.out.println(JsonUtil.getJsonStrFromXML(xml));
    }
} 

entity:

package com.bxw.entity;

import java.util.Date;

public class Person {
    private String name;
    private int age;
    private Date dateAttr;
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public int getAge() {
        return age;
    }
    public void setAge(int age) {
        this.age = age;
    }
    public Date getDateAttr() {
        return dateAttr;
    }
    public void setDateAttr(Date dateAttr) {
        this.dateAttr = dateAttr;
    }

}
package com.bxw.entity;

import java.util.List;

public class MyBean {
    private String key;
    private List<Person> data;
    public String getKey() {
        return key;
    }
    public void setKey(String key) {
        this.key = key;
    }
    public List<Person> getData() {
        return data;
    }
    public void setData(List<Person> data) {
        this.data = data;
    }

}
package com.bxw.demo;

public class Util {
    public static String YYYY_MM_DD_HH_MM_ss="yyyy-MM-dd HH:mm:ss";

    public static String YYYY_MM_DD="yyyy-MM-dd";

    public static String YYYYMMDDHHMMSS="yyyyMMddHHmmss";

    public static String HHMMss="HHmmss";

    public static String HH_MM_ss="HH:mm:ss";

    public static String YYYYMMDD="yyyyMMdd";
}
时间: 2024-10-21 07:14:53

jsonUtil的相关文章

JsonUtil(工具类)

WebBuilder使用的操作json的jar包是org.json,下面是相关的文档及源码,搜索就可得 文档:http://www.json.org/javadoc/org/json/JSONObject.html 源码:https://github.com/douglascrockford/JSON-java 本文默认读者熟练使用JSON,了解JSON语法,开始正题: 从文档和源码看来org.json没有多少东西,的确他就是很简单,没有多少东西,在这几个仅有的类中,我们要经常使用也只有JSON

JsonUtil.java

package com.xxx.common.util; import java.io.IOException; import org.apache.commons.lang.StringUtils; import org.codehaus.jackson.JsonParseException; import org.codehaus.jackson.JsonParser; import org.codehaus.jackson.map.DeserializationConfig; import

JsonUtil工具类

package comm; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Collection; import java.util.Date; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import net.sf.ezmorph.M

JsonUtil对象与json互转

OrderDto orderDto = JsonUtil.json2Object(json,     new TypeRef<OrderDto>() {     }); package com.sf.module.bspcommon.util.json; import java.io.IOException; import java.text.SimpleDateFormat; import java.util.TimeZone; import org.slf4j.Logger; import

基于lucene的案例开发:JsonUtil &amp; XmlUtil

转载请注明出处:http://blog.csdn.net/xiaojimanman/article/details/43194015 从这篇博客开始第二大部分就算正式开始了,不过在介绍搜索后台之前,还是先介绍写可能使用的大工具类,这样在后面的搜索后台介绍中,就不会穿插其他的内容介绍.这篇就主要介绍两个工具类:json.xml格式数据处理类. JSON 在前后台数据通信过程中,json数据格式是一种比较常用的方式.将javabean转化为json格式字符串,可以通过简单的字符串拼接,也可以使用第三

JSONUtil.bean2Json()报Property &#39;key&#39; of class has no read method. SKIPPED的问题处理

错误警告信息描述: net.sf.json.JSONObject.defaultBeanProcessing(JSONObject.java:769) Property 'handler' of class com.vrv.cems.mgr.domain.Manager_$$_javassist_182 has no read method. SKIPPED 问题分析: JsonUtil.bean2Json(queryHistogramVO,new String[]{})); 将VO对象转换成J

利用Jackson封装常用JsonUtil工具类

在日常的项目开发中,接口与接口之间.前后端之间的数据传输一般都是使用JSON格式,那必然会封装一些常用的Json数据转化的工具类,本文讲解下如何利用Jackson封装高复用性的Json转换工具类. 转换格式属性配置 首先,我们需要对Json对象转换自定义些常用配置属性,封装成适合项目接口规则的工具类.代码如下: @Slf4j public class JsonUtil { private static ObjectMapper objectMapper = new ObjectMapper();

JSONUtil(JAVA对象/List与json互转,xml与json互转)

package com.chauvet.utils.json; import java.io.BufferedReader; import java.io.File; import java.io.FileInputStream; import java.io.FileWriter; import java.io.InputStreamReader; import java.util.List; import net.sf.json.JSONArray; import net.sf.json.J

Android FastJson与不规范JSON引发的血案

去公司实习了,没多少时间更博客了,距离上一篇博客也有一个来月了.看标题,应该可以看出,这篇文章是讲一个坑,以及如何填坑. 坑是什么?有两个坑,其一是fastjson的bug,其二是不规范的json字符串.如何填坑,不要着急,后文详细说明. 首先,我们看一个json字符串 { "doubleParam": 4.875, "floatParam": 2.76, "extra": { "doubleParam": 12.23, &q