Json-Lib的使用

2017-08-28  本文已影响15人  Ethan_Walker

1. 数组/集合/Map/JavaBean对象 ==> Json 字符串

JSONObject jsonObject = JSONObject.fromObject(Object);
jsonObject.toString();

数组:

int[] intArray
[1,4,5]
boolean[] boolArray
[true,false,true]
int[][] int2Array
[[1,2],[3,4]]
float[] floatArray
[0.1,0.2,0.3]
String[] strArray
["hello","hebut","xiapi"]

集合:

List list1
["first","second"]
List<Student> list2
[{"age":10,"sex":"男","userName":"xiapi1"},{"age":11,"sex":"女","userName":"xiapi2"},{"age":12,"sex":"男","userName":"xiapi3"}]

Map

Map map1
{"arr":["a","b"],"int":1,"name":"json","func":function(i){ return this.arr[i]; },"bool":true}
Map<String,Student> map2
{"k3":{"age":13,"sex":"男","userName":"xiapi3"},"k1":{"age":10,"sex":"男","userName":"xiapi1"},"k2":{"age":12,"sex":"女","userName":"xiapi2"}}

JavaBean:

{"age":22,"sex":"男","userName":"xiapi"}

2. xml==>Json

 @Test
    public void xmlTojson(){
        String s="<student>
                        <name id='n1'>xiapi</name>
                        <sex class='s1'>男</sex>
                        <age>20</age>
                    </student>";
        XMLSerializer x =new XMLSerializer();
        JSON json = x.read(s);
        System.out.println("XmlToJson");
        System.out.println(json.toString());
    }

结果:

XmlToJson
{"name":{"@id":"n1","#text":"xiapi"},"sex":"男","age":"20"}

3. Json 字符串转 JavaBean


    @Test
    public void jsonStrToBean(){
        String customerStr = "{'cust_name':'ethan'}";
        JSONObject jsonObject = JSONObject.fromObject(customerStr);
        Customer custoemr = (Customer) JSONObject.toBean(jsonObject, Customer.class);
        System.out.println(custoemr);
    }

结果:

Customer{cust_id=null, cust_name='ethan', cust_user_id=null, cust_create_id=null, cust_source='null', cust_industry='null', cust_level='null', cust_linkman='null', cust_phone='null', cust_mobile='null', cust_zipcode='null', cust_address='null', cust_createtime=null}

上一篇下一篇

猜你喜欢

热点阅读