Jason and Java Object conversion examples

Source: Internet
Author: User

1. Engineering

2. Code:

Jsonutil.java

Package Com.my.json;import Java.util.arraylist;import Java.util.list;import net.sf.json.jsonarray;import             Net.sf.json.jsonobject;public class Jsonutil {/** * Gets a Java object from a JSON object character format * * @param jsonstring * JSON String * * @param POJOCALSS * Java Object class * * @return * * Public stat        IC Object Jsonstring2object (String jsonstring, Class pojocalss) {object Pojo;        Jsonobject jsonobject = Jsonobject.fromobject (jsonstring);        Pojo = Jsonobject.tobean (Jsonobject, POJOCALSS);    return Pojo;      /** * * Convert Java objects to JSON strings <br> * Support complex types: Java beans have both properties and list * * @param javaobj *        * @return */public static String object2jsonstring (Object javaobj) {jsonobject json;        JSON = Jsonobject.fromobject (javaobj);    return json.tostring (); /** * * Get a list of Java objects from the JSON object collection expression * * @param jsonstring * * @param pojoclass *     * @return */public static List jsonlist2javalist (String jsonstring, Class pojoclass) {Jsonarray Jsona        Rray = Jsonarray.fromobject (jsonstring);        Jsonobject Jsonobject;        Object Pojovalue;        List List = new ArrayList ();            for (int i = 0; i < jsonarray.size (); i++) {jsonobject = Jsonarray.getjsonobject (i);            Pojovalue = Jsonobject.tobean (Jsonobject, Pojoclass);        List.add (Pojovalue);    } return list; /** * * Get a list of Java objects from the JSON object collection expression * * @param jsonstring * * @param pojoclass * * @return */public static String javalist2jsonlist (List list) {Jsonarray Jsonarray = Jsonarray.fromobject (li        ST);    return jsonarray.tostring (); }
123456789101112131415161718192021 /**<br>* Json转化为map<br>*/<br>publicstaticMap<String, Object> parseJSON2Map(String jsonStr){          Map<String, Object> map = newHashMap<String, Object>();          //最外层解析          JSONObject json = JSONObject.fromObject(jsonStr);          for(Object k : json.keySet()){              Object v = json.get(k);               //如果内层还是数组的话,继续解析              if(v instanceofJSONArray){                  List<Map<String, Object>> list = newArrayList<Map<String,Object>>();                  Iterator<JSONObject> it = ((JSONArray)v).iterator();                  while(it.hasNext()){                      JSONObject json2 = it.next();                      list.add(parseJSON2Map(json2.toString()));                                  map.put(k.toString(), list);              } else                map.put(k.toString(), v);                              returnmap;      }

  

}

Person.java

Package Com.my.json;import Java.util.arraylist;import Java.util.list;public class Person {private String name;    Private list<person> List = new arraylist<person> ();    Public list<person> getList () {return List;    } public void setlist (list<person> list) {this.list = list;                } @Override Public String toString () {return ' person [name= + name + ', num= "+ num +", sex= "+ Sex    + ", age=" + Age + "]";    } private int num;    Private String sex;    private int age; Public person () {//TODO auto-generated constructor stubs} public person (string name, int num, string sex, I        NT age) {super ();        THIS.name = name;        This.num = num;        This.sex = sex;    This.age = age;    } public String GetName () {return name;    } public void SetName (String name) {this.name = name;    } public int Getnum () {return num; } public void setnum (int num) {this.num = num;    } public String Getsex () {return sex;    public void Setsex (String sex) {this.sex = sex;    } public int Getage () {return age;    public void Setage (int.) {this.age = age; }}

Test.java

Package Com.my.json;import Java.util.arraylist;import Java.util.list;import java.util.map;import        Net.sf.json.jsonobject;public class Test {public static void main (string[] args) {//Convert a Java object to a JSON string        Person p = new person ("GU1", 123, "male", 23);        String str = jsonutil.object2jsonstring (p);        System.out.println (str);        Convert a JSON string to a Java object string s = "{\" age\ ": 23,\" name\ ": \" gu1\ ", \" num\ ": 123,\" sex\ ": \" Male\ "}";        person P2 = (person) jsonutil.jsonstring2object (s, person.class);        System.out.println (p2);        Converts an object list to a JSON list list<person> list = new arraylist<person> ();            for (int i = 0; i < 5; i++) {Person persion = new Person ("Zhang" + i, 1 + i, "man" + I, 1 + i);        List.add (persion);        } String jsonlist = jsonutil.javalist2jsonlist (list);        System.out.println (jsonlist); Convert a JSON list to a Java list String jst = "[{\" age\ ": 1,\" list\ ": [],\" name\ ": \" Zhang0\ ", \" num\ ": 1,\" sex\ ": \" man0\ "},{\" age\ ": 2,\" list\ ": [],\" name\ ": \" zhang1\ ", \" num\ ": 2,\" sex\ ": \" man1\ "},{\" age\ " : 3,\ "list\": [],\ "name\": \ "zhang2\", \ "num\": 3,\ "sex\": \ "man2\"},{\ "age\": 4,\ "list\": [],\ "name\": \ "zhang3\", \ "        Num\ ": 4,\" sex\ ": \" man3\ "},{\" age\ ": 5,\" list\ ": [],\" name\ ": \" zhang4\ ", \" num\ ": 5,\" sex\ ": \" Man4\ "}]";        list<person> L = (list<person>) jsonutil.jsonlist2javalist (JST, Person.class);        System.out.println (L.size ());        Complex type to Json:java Bean has both attributes and list (often seen in the project) list<person> List2 = new arraylist<person> ();            for (int i = 0; i < i++) {person persion = new Person ("Zhang" + i, 1 + i, "man" + I, 1 + i);        List2.add (persion);        } Person me = new Person ("Zhang", 1, "Man", 1);        Me.setlist (LIST2);        String str2 = jsonutil.object2jsonstring (Me);        System.out.println (STR2); Complex Type Java:json has both attributes and list (often seen in the project) String ss = "{\" age\ ": 1,\" list\ ": [{\" AGE\ ": 1,\" list\ ": [],\" name\ ": \" zhang0\ ", \" num\ ": 1,\" sex\ ": \" man0\ "},{\" age\ ": 2,\" list\ ": [],\" name\ ": \" zhang1\ ", \ "Num\": 2,\ "sex\": \ "man1\"},{\ "age\": 3,\ "list\": [],\ "name\": \ "zhang2\", \ "num\": 3,\ "sex\": \ "man2\"},{\ "age\": 4,\ "List\": [],\ "name\": \ "zhang3\", \ "num\": 4,\ "sex\": \ "man3\"},{\ "age\": 5,\ "list\": [],\ "name\": \ "zhang4\", \ "Num\" : 5,\ "sex\": \ "man4\"},{\ "age\": 6,\ "list\": [],\ "name\": \ "zhang5\", \ "num\": 6,\ "sex\": \ "man5\"},{\ "age\": 7,\ "list\ ": [],\" name\ ": \" zhang6\ ", \" num\ ": 7,\" sex\ ": \" man6\ "},{\" age\ ": 8,\" list\ ": [],\" name\ ": \" zhang7\ ", \" num\ ": 8,\" Sex\ ": \" man7\ "},{\" age\ ": 9,\" list\ ": [],\" name\ ": \" zhang8\ ", \" num\ ": 9,\" sex\ ": \" man8\ "},{\" age\ ": 10,\" list\ ": []        , \ "name\": \ "zhang9\", \ "num\": 10,\ "sex\": \ "man9\"}],\ "name\": \ "zhang\", \ "num\": 1,\ "sex\": \ "man\"} ";                 Map map = (map) jsonobject.fromobject (ss);        System.out.println ("------------------------------");        SYSTEM.OUT.PRINTLN (map);        String name = (string) map.get ("name");      int num = (Integer) map.get ("num");  String sex = (string) map.get ("Sex");        int age = (Integer) map.get ("Age");        System.out.println ("name=" +name);        System.out.println ("num=" + "num");        System.out.println ("sex=" + "sex");        System.out.println ("age=" + "Age");        System.out.println ("list=" +map.get ("List")); Getting the list string, and then converting it to a Java object, is actually built again into Java bean string liststr = Map.get ("list"). ToString ();//must use ToString, not strong to Li        st<person> ll = jsonutil.jsonlist2javalist (Liststr, Person.class);        Build a new bean: I don't know if there are any other scenarios, whether or not to build the person PP = new person (name,num,sex,age);        Pp.setlist (LL);        Output bean for (person ps:pp.getList ()) {System.out.println (Ps.getname ()); }                }}

Output:

{"Age": $, "list": [], "name": "GU1", "num": 123, "sex": "Male"}
person [Name=gu1, num=123, Sex=male, age=23]
[{"Age": 1, "list": [], "name": "ZHANG0", "num": 1, "Sex": "Man0"},{"Age": 2, "list": [], "name": "Zhang1", "num": 2, "Sex": " Man1 "},{": 3, "list": [], "name": "Zhang2", "num": 3, "Sex": "Man2"},{"Age": 4, "list": [], "name": "Zhang3", "num": 4, " Sex ":" Man3 "},{" Age ": 5," list ": []," name ":" Zhang4 "," num ": 5," Sex ":" Man4 "}]
5
{"Age": 1, "list": [{' Age ': 1, "list": [], "name": "ZHANG0", "num": 1, "Sex": "Man0"},{"Age": 2, "list": [], "name": "Zhang1", " Num ": 2," Sex ":" Man1 "},{" Age ": 3," list ": []," name ":" Zhang2 "," num ": 3," Sex ":" Man2 "},{" Age ": 4," list ": []," name ":" Zhang3 "," num ": 4," Sex ":" Man3 "},{" Age ": 5," list ": []," name ":" Zhang4 "," num ": 5," Sex ":" Man4 "},{" Age ": 6," list ": []," Name ":" Zhang5 "," num ": 6," Sex ":" Man5 "},{" Age ": 7," list ": []," name ":" Zhang6 "," num ": 7," Sex ":" Man6 "},{" age ": 8," list ": [], "name": "Zhang7", "num": 8, "Sex": "Man7"},{"Age": 9, "list": [], "name": "Zhang8", "num": 9, "Sex": "Man8"},{"age": 10, " List ": []," name ":" ZHANG9 "," num ": Ten," Sex ":" Man9 "}]," name ":" Zhang "," num ": 1," Sex ":" Man "}
------------------------------
{"Age": 1, "list": [{' Age ': 1, "list": [], "name": "ZHANG0", "num": 1, "Sex": "Man0"},{"Age": 2, "list": [], "name": "Zhang1", " Num ": 2," Sex ":" Man1 "},{" Age ": 3," list ": []," name ":" Zhang2 "," num ": 3," Sex ":" Man2 "},{" Age ": 4," list ": []," name ":" Zhang3 "," num ": 4," Sex ":" Man3 "},{" Age ": 5," list ": []," name ":" Zhang4 "," num ": 5," Sex ":" Man4 "},{" Age ": 6," list ": []," Name ":" Zhang5 "," num ": 6," Sex ":" Man5 "},{" Age ": 7," list ": []," name ":" Zhang6 "," num ": 7," Sex ":" Man6 "},{" age ": 8," list ": [], "name": "Zhang7", "num": 8, "Sex": "Man7"},{"Age": 9, "list": [], "name": "Zhang8", "num": 9, "Sex": "Man8"},{"age": 10, " List ": []," name ":" ZHANG9 "," num ": Ten," Sex ":" Man9 "}]," name ":" Zhang "," num ": 1," Sex ":" Man "}
Name=zhang
Num=num
Sex=sex
Age=age
List=[{"Age": 1, "list": [], "name": "ZHANG0", "num": 1, "Sex": "Man0"},{"Age": 2, "list": [], "name": "Zhang1", "num": 2, "sex ":" Man1 "},{" Age ": 3," list ": []," name ":" Zhang2 "," num ": 3," Sex ":" Man2 "},{" Age ": 4," list ": []," name ":" Zhang3 "," num ": 4, "Sex": "Man3"},{"Age": 5, "list": [], "name": "Zhang4", "num": 5, "Sex": "Man4"},{"Age": 6, "list": [], "name": "Zhang5", "num ": 6," Sex ":" Man5 "},{" Age ": 7," list ": []," name ":" Zhang6 "," num ": 7," Sex ":" Man6 "},{" age ": 8," list ": []," name ":" Zhang7 ", "Num": 8, "Sex": "Man7"},{"Age": 9, "list": [], "name": "Zhang8", "num": 9, "Sex": "Man8"},{"age": Ten, "List": [], "name": " ZHANG9 "," num ": Ten," Sex ":" Man9 "}]
Zhang0
Zhang1
Zhang2
Zhang3
Zhang4
Zhang5
Zhang6
Zhang7
Zhang8
Zhang9

Jason and Java Object conversion examples

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

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.