Json-lib使用

來源:互聯網
上載者:User

標籤:slist   als   blank   字元   ack   實現   對象數組   excludes   rom   

 

  • Json-lib

Json-lib 是一個 Java 類庫(官網:http://json-lib.sourceforge.net/)可以實現如下功能:

  • 轉換 javabeans, maps, collections, java arrays 和 XML 成為 json 格式資料
  • 轉換 json 格式資料成為 javabeans 對象

Json-lib 需要的 jar 包

  • commons-beanutils-1.8.3.jar
  • commons-collections-3.2.1.jar
  • commons-lang-2.6.jar
  • commons-logging-1.1.1.jar
  • ezmorph-1.0.6.jar
  • json-lib-2.4-jdk15.jar

 

  • Json-lib 的使用

1. 將 Array 解析成 Json 串。

@Test
public void arrToJson() {
/**
* 將Array轉化成Json串
*/
String[] str = {"Json", "Json-lib", "Jackson", "Xml"};
JSONArray json = JSONArray.fromObject(str);
System.out.println(json);

/**
* 對象數組轉為Json
*/
Person[] ps = { new Person(1, "略略", false, new Date(), Arrays.asList(new String[] {"打球", "遊戲", "動漫"})),
new Person(2, "哈哈", false, new Date(), Arrays.asList(new String[] {"打球"}))
};
json = JSONArray.fromObject(ps);
System.out.println(json);

/**
* 將List集合轉為Json
*/
List<Person> plist = new ArrayList<Person>();
plist.add(new Person(1, "略略", false, new Date(), Arrays.asList(new String[] {"打球", "遊戲", "動漫"})));
plist.add(new Person(2, "哈哈", false, new Date(), Arrays.asList(new String[] {"打球"})));
json = JSONArray.fromObject(ps);
System.out.println(json);

}

運行結果如下:

["Json","Json-lib","Jackson","Xml"]
[{"birthday":{"date":14,"day":5,"hours":19,"minutes":29,"month":3,"seconds":56,"time":1492169396320,"timezoneOffset":-480,"year":117},"gender":false,"hobby":["打球","遊戲","動漫"],"id":1,"name":"略略"},{"birthday":{"date":14,"day":5,"hours":19,"minutes":29,"month":3,"seconds":56,"time":1492169396320,"timezoneOffset":-480,"year":117},"gender":false,"hobby":["打球"],"id":2,"name":"哈哈"}]
[{"birthday":{"date":14,"day":5,"hours":19,"minutes":29,"month":3,"seconds":56,"time":1492169396320,"timezoneOffset":-480,"year":117},"gender":false,"hobby":["打球","遊戲","動漫"],"id":1,"name":"略略"},{"birthday":{"date":14,"day":5,"hours":19,"minutes":29,"month":3,"seconds":56,"time":1492169396320,"timezoneOffset":-480,"year":117},"gender":false,"hobby":["打球"],"id":2,"name":"哈哈"}]

2. 將 JavaBean/Map 解析成 JSON 串。 使用JSONObject 解析:

@Test
public void beanToJson() {

/**
* 對象轉化為Json
*/
Person p = new Person(1, "略略", false, new Date(), Arrays.asList(new String[] {"打球", "遊戲", "動漫"}));
JSONObject json = JSONObject.fromObject(p);
System.out.println(json);

/**
* 解析map
*/
Map<String, Object> map = new HashMap<String, Object>();
map.put("name", "董事三");
map.put("age", 24);
json = JSONObject.fromObject(map);
System.out.println(json);

}

運行結果如下:

{"birthday":{"date":14,"day":5,"hours":19,"minutes":38,"month":3,"seconds":22,"time":1492169902753,"timezoneOffset":-480,"year":117},"gender":false,"hobby":["打球","遊戲","動漫"],"id":1,"name":"略略"}
{"age":24,"name":"董事三"}

3. 使用 JsonConfig 過慮屬性:適用於 JavaBean/Map

@Test
public void jsonConfig() {
/**
* 使用jsonConfig過濾屬性
*/
Person p = new Person(1, "略略", false, new Date(), Arrays.asList(new String[] {"打球", "遊戲", "動漫"}));
JsonConfig config = new JsonConfig();
config.setExcludes(new String[] {"birthday"});
JSONObject json = JSONObject.fromObject(p, config);
System.out.println(json);
}

運行結果如下,在運行結果中我們可以看到 name 屬性被過濾掉了:

{"gender":false,"hobby":["打球","遊戲","動漫"],"id":1,"name":"略略"}

4. 將 Json 串轉換成 Array:

@Test
public void jsonToArr() {

/**
* json轉換成一般數組
*/
String[] str = {"Json", "Json-lib", "Jackson", "Xml"};
JSONArray json = JSONArray.fromObject(str);

Object strs = JSONArray.toArray(json);
System.out.println(strs);
System.out.println(Arrays.asList((Object[])strs));

List<Person> plist = new ArrayList<Person>();
plist.add(new Person(1, "略略", false, new Date(), Arrays.asList(new String[] {"打球", "遊戲", "動漫"})));
plist.add(new Person(2, "哈哈", false, new Date(), Arrays.asList(new String[] {"打球"})));
json = JSONArray.fromObject(plist);

List<Person> ps = (List<Person>) JSONArray.toCollection(json, Person.class);
for (Person person : ps) {
System.out.println(person);
}
}

運行結果如下:

[Ljava.lang.Object;@39e87719
[Json, Json-lib, Jackson, Xml]
Person [id=1, name=略略, gender=false, birthday=Fri Apr 14 20:18:29 CST 2017, hobby=[打球, 遊戲, 動漫]]
Person [id=2, name=哈哈, gender=false, birthday=Fri Apr 14 20:18:29 CST 2017, hobby=[打球]]

5. 將 Json 串轉成 JavaBean:

@Test
public void jsonToBean() {
/**
* json轉化為javabean
*/
Person p = new Person(1, "略略", false, new Date(), Arrays.asList(new String[] {"打球", "遊戲", "動漫"}));
JSONObject json = JSONObject.fromObject(p);

Object o = JSONObject.toBean(json, Person.class);
System.out.println(o);



}

運行結果如下:

2017-4-14 20:19:51 net.sf.json.JSONObject toBean
資訊: Property ‘day‘ of class java.util.Date has no write method. SKIPPED.
2017-4-14 20:19:51 net.sf.json.JSONObject toBean
資訊: Property ‘timezoneOffset‘ of class java.util.Date has no write method. SKIPPED.
Person [id=1, name=略略, gender=false, birthday=Fri Apr 14 20:19:51 CST 2017, hobby=[打球, 遊戲, 動漫]]

在將 Json 形式的字串轉換為 JavaBean 的時候需要注意 JavaBean 中必須有無參建構函式,否則會報如下找不到初始化方法的錯誤:

Exception in thread "main" net.sf.json.JSONException: java.lang.NoSuchMethodException: cn.sunzn.json.Person.<init>()   at net.sf.json.JSONObject.toBean(JSONObject.java:288)   at net.sf.json.JSONObject.toBean(JSONObject.java:233)   at cn.sunzn.json.JsonLib.main(JsonLib.java:23)Caused by: java.lang.NoSuchMethodException: cn.sunzn.json.Person.<init>()   at java.lang.Class.getConstructor0(Unknown Source)   at java.lang.Class.getDeclaredConstructor(Unknown Source)   at net.sf.json.util.NewBeanInstanceStrategy$DefaultNewBeanInstanceStrategy.newInstance(NewBeanInstanceStrategy.java:55)   at net.sf.json.JSONObject.toBean(JSONObject.java:282)   ... 2 more

Json-lib使用

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.