1, the need jar package Json-lib.jar
Download Link:
http://sourceforge.net/projects/json-lib/files/json-lib/
This package also requires the following dependency packages,
Commons-lang.jar
Commons-beanutils . Jar
Commons-collections. Jar
Commons-logging. Jar
Ezmorph. Jar
2, create the JavaBean file, take the following example:
<span style= "FONT-SIZE:18PX;" >package Com.gdhdcy.whp;public class Person_bean {public int id;public int getId () {return ID;} public void setId (int id) {this.id = ID;} Public String GetName () {return name;} public void SetName (String name) {this.name = name;} Public String Getsex () {return sex;} public void Setsex (String sex) {this.sex = sex;} Public String Getmoblie () {return moblie;} public void Setmoblie (String moblie) {This.moblie = Moblie;} public string Name;public string Sex;public string Moblie;} </span>
3. Bean/list/map generates JSON code:
<span style= "FONT-SIZE:18PX;" >package com.gdhdcy.whp;import java.util.arraylist;import Java.util.hashmap;import java.util.List;import Net.sf.json.jsonarray;import Net.sf.json.jsonobject;public class Json_create {public static void main (String args[]) {/ /javabean generates Jsonperson_bean pb=new Person_bean ();p B.setid (1);p b.setname ("Wang");p b.setsex ("male");p B.setmoblie (" 1341234568 "); Jsonobject Jsonobject=jsonobject.fromobject (PB); System.out.println (Jsonobject.tostring ());//result//{"id": 1, "Moblie": "1341234568", "name": "Wang", "Sex": "Male"}// List Generation Jsonperson_bean pb1=new Person_bean ();p B1.setid (2);p b1.setname ("wang1");p b1.setsex ("female");p B1.setmoblie (" 13123323 ");p Erson_bean pb2=new Person_bean ();p B2.setid (3);p b2.setname (" Wang3 ");p b2.setsex (" female ");p B2.setmoblie (" 13232343673 "); List<object> list=new arraylist<object> (); List.add (PB1); List.add (PB2); Jsonarray jsonarray=jsonarray.fromobject (list); System.out.println (Jsonarray.tostring ());/** * Results such as the following *///[{"id": 2, "Moblie": "13123323", "name": "Wang1", "Sex": "Female"},{"id": 3, "Moblie": "13232343673", "name": "Wang3", "Sex": "female"}]//map converted to jsonhashmap<string, string> map=new Hashmap<string, String> () map.put ("1", "Hai"), Map.put ("2", "Tian"), Map.put ("3", "Zhi"); Jsonobject jsonobject1=jsonobject.fromobject (map); System.out.println (Jsonobject1.tostring ());//Results://{"3": "Zhi", "2": "Tian", "1": "Hai"}}}</span>
4, the result of implementation:
{"id": 1, "Moblie": "1341234568", "name": "Wang", "Sex": "Male"}
[{"id": 2, "Moblie": "13123323", "name": "Wang1", "Sex": "female"},{"id": 3, "Moblie": "13232343673", "name": "Wang3", "Sex": "Female" }]
{"3": "Zhi", "2": "Tian", "1": "Hai"}
Copyright notice: This article Bo Master original articles, blogs, without consent may not be reproduced.
JSON learning experience--third party jar package implementation Bean, List, map create JSON format