Java中Json字符串转对象方法

Java利用Json-lib包进行JSON对象转换

1.  json转Arrays对象

public void json2arrays() {
    String json1 = "['first','second']";
    JSONArray jsonArray1 = (JSONArray) JSONSerializer.toJSON(json1);
    JsonConfig jsonConfig = new JsonConfig();
    jsonConfig.setArrayMode(JsonConfig.MODE_OBJECT_ARRAY);
    Object[] output1 = (Object[]) JSONSerializer.toJava(jsonArray1, jsonConfig);
    Object[] expected = new Object[] {
        "first",
        "second"
    };
    ArrayAssertions.assertEquals(expected, output1);
    System.out.println("Object[]");
    System.out.println(output1.length);
    System.out.println(output1[1]);
    String json2 = "[[1,2],[3,4]]";
    JSONArray jsonArray2 = JSONArray.fromObject(json2);
    Object[][] output2 = (Object[][]) JSONArray.toArray(jsonArray2);
    System.out.println("Object[][]");
    System.out.println(output2.length);
    System.out.println(output2[0][0]);
}

执行结果:

Object[]
2
second
Object[][]
2
1

2. Json转换Collections对象

public void json2collections() {
    String json1 = "['first','second']";
    JSONArray jsonArray1 = (JSONArray) JSONSerializer.toJSON(json1);
    List output1 = (List) JSONSerializer.toJava(jsonArray1);
    System.out.println("List");
    System.out.println(output1.get(0));
    String json2 = "[{'age':10,'sex':'男','userName':'xiapi1'},{'age':11,'sex':'女','userName':'xiapi2'}]";
    JSONArray jsonArray2 = JSONArray.fromObject(json2);
    List < Student > output2 = JSONArray.toList(jsonArray2, Student.class);
    System.out.println("List<Student>");
    System.out.println(output2.size());
    System.out.println(output2.get(0));
    System.out.println(output2.get(0).getUserName());
}

执行结果:

List
first
List<Student>
2
com.hebut.jsonlib.Student@16f144c
xiapi1

3. Json转换Map对象

public void json2map() {
    String json1 = "{'arr':['a','b'],'int':1,'name':'json','bool':true}";
    JSONObject jsonObject1 = JSONObject.fromObject(json1);
    Map typeMap1 = new HashMap();
    typeMap1.put("arr", String[].class);
    typeMap1.put("int", Integer.class);
    typeMap1.put("name", String.class);
    typeMap1.put("bool", Boolean.class);
    Map output1 = (Map) JSONObject.toBean(jsonObject1, Map.class, typeMap1);
    System.out.println("Map");
    System.out.println(output1.size());
    System.out.println(output1.get("name"));
    System.out.println(output1.get("arr"));
    String json2 = "{'k1':{'age':10,'sex':'男','userName':'xiapi1'},'k2':{'age':12,'sex':'女','userName':'xiapi2'}}";
    JSONObject jsonObject2 = JSONObject.fromObject(json2);
    Map < String,
    Class < ?>>typeMap2 = new HashMap < String,
    Class < ?>>();
    Map < String,
    Student > output2 = (Map < String, Student > ) JSONObject.toBean(jsonObject2, Map.class, typeMap2);
    System.out.println("Map<String,Student>");
    System.out.println(output2.size());
    System.out.println(output2.get("k1"));

    //先往注册器中注册变换器,需要用到ezmorph包中的类
    MorpherRegistry morpherRegistry = JSONUtils.getMorpherRegistry();
    Morpher dynaMorpher = new BeanMorpher(Student.class, morpherRegistry);
    morpherRegistry.registerMorpher(dynaMorpher);
    System.out.println(((Student) morpherRegistry.morph(Student.class, output2.get("k2"))).getUserName());
}

执行结果:

Map
4
json
[a, b]
Map<String,Student>
2
net.sf.ezmorph.bean.MorphDynaBean@5b8827[{sex=男, age=10, userName=xiapi1}]
xiapi2

4. Json转换Bean对象

public void json2bean() {
    //简单对象
    String json1 = "{'age':22,'sex':'男','userName':'xiapi'}";
    JSONObject jsonObject1 = JSONObject.fromObject(json1);
    Student output1 = (Student) JSONObject.toBean(jsonObject1, Student.class);
    System.out.println("Student");
    System.out.println(output1.getUserName());
    //复杂对象
    String json2 = "{'date':'2012-05-21 13:03:11','name':'计算机应用1班','students':[{'age':10,'sex':'男','userName':'xiapi1'},{'age':11,'sex':'女','userName':'xiapi2'}]}";
    //转为日期
    String[] DATE_FORMAT = {
        "yyyy-MM-dd HH:mm:ss"
    };
    MorpherRegistry morpherRegistry = JSONUtils.getMorpherRegistry();
    morpherRegistry.registerMorpher(new DateMorpher(DATE_FORMAT));
    JSONObject jsonObject2 = JSONObject.fromObject(json2);
    Map typeMap1 = new HashMap();
    typeMap1.put("date", Date.class);
    typeMap1.put("name", String.class);
    typeMap1.put("students", Student.class);
    Class output2 = (Class) JSONObject.toBean(jsonObject2, Class.class, typeMap1);
    System.out.println("Class");
    System.out.println(output2.getName());
    System.out.println(output2.getDate());
    System.out.println(output2.getStudents().get(0).getUserName());
}

执行结果:

Student
xiapi
Class
计算机应用1班
Mon May 21 13:03:11 CST 2012
xiapi1

5. Json转换Xml对象

public void json2xml() {
    String json1 = "{'age':22,'sex':'男','userName':'xiapi'}";
    JSONObject jsonObj = JSONObject.fromObject(json1);
    XMLSerializer x = new XMLSerializer();
    String xml = x.write(jsonObj);
    System.out.println("XML");
    System.out.println(xml);
}

执行结果:

XML
<?xml version="1.0" encoding="UTF-8"?>
<o><age type="number">22</age><sex type="string">男</sex><userName type="string">xiapi</userName></o>

6. 将json字符串转成Java对象

public void readJSON2Bean() {
    fail("==============JSON Object String >>> Java Bean ==================");
    String json = "{\"address\":\"chian\",\"birthday\":{\"birthday\":\"2010-11-22\"}," +
        "\"email\":\"email@123.com\",\"id\":22,\"name\":\"tom\"}";
    jsonObject = JSONObject.fromObject(json);
    Student stu = (Student) JSONObject.toBean(jsonObject, Student.class);
    fail(stu.toString());
}

执行结果:

==============JSON Object String >>> Java Bean ==================
tom#22#chian#2010-11-22#email@123.com

7. 将json字符串转换成动态Java对象(MorphDynaBean)

public void readJSON2DynaBean() {
    try {
        fail("==============JSON Object String >>> Java MorphDynaBean ==================");
        String json = "{\"address\":\"chian\",\"birthday\":{\"birthday\":\"2010-11-22\"}," + "\"email\":\"email@123.com\",\"id\":22,\"name\":\"tom\"}";
        JSON jo = JSONSerializer.toJSON(json);
        Object o = JSONSerializer.toJava(jo); //MorphDynaBean
        fail(PropertyUtils.getProperty(o, "address").toString());
        jsonObject = JSONObject.fromObject(json);
        fail(jsonObject.getString("email"));
        o = JSONSerializer.toJava(jsonObject); //MorphDynaBean
        fail(PropertyUtils.getProperty(o, "name").toString());
    } catch(IllegalAccessException e) {
        e.printStackTrace();
    } catch(InvocationTargetException e) {
        e.printStackTrace();
    } catch(NoSuchMethodException e) {
        e.printStackTrace();
    }
}

执行结果:

==============JSON Object String >>> Java MorphDynaBean =============
chian
email@123.com
tom

8. JSON字符串转成Java的List集合

public void readJSON2List() {
    try {
        fail("==============JSON Arry String >>> Java List ==================");
        String json = "{\"address\":\"chian\",\"birthday\":{\"birthday\":\"2010-11-22\"}," + "\"email\":\"email@123.com\",\"id\":22,\"name\":\"tom\"}";
        json = "[" + json + "]";
        jsonArray = JSONArray.fromObject(json);
        List < Student > list = JSONArray.toList(jsonArray, Student.class);
        System.out.println(list.size());
        System.out.println(list.get(0));
        list = JSONArray.toList(jsonArray);
        System.out.println(list.size());
        System.out.println(list.get(0)); //MorphDynaBean
    } catch(Exception e) {
        e.printStackTrace();
    }
}

执行结果:

==============JSON Arry String >>> Java List ==================
1
tom#22#chian#2010-11-22#email@123.com
1
net.sf.ezmorph.bean.MorphDynaBean@141b571[{id=22, birthday=net.sf.ezmorph.bean.MorphDynaBean@b23210[{birthday=2010-11-22}], address=chian, email=email@123.com, name=tom}]


版权声明:本文为JAVASCHOOL原创文章,未经本站允许不得转载。