When JSON is converted to an object, the JSON key corresponds to field one by one in the Java class. If there is no Java field on the map, the default value is populated on that data type, such as int 0,string null, and so on.
JSON key without mapping is displayed with a warning when the program ends, telling the programmer that the key value is not mapped
ImportNet.sf.json.JSONObject; Public classMainClass { Public Static voidMain (string[] args) {Testjsonbean (); } /*** Java objects and JSON objects are converted to each other*/ Private Static voidTestjsonbean () {/*** Create Java Objects*/Student Student=NewStudent (); Student.setid (1); Student.setname ("Jag"); Student.setsex ("Man"); Student.setage (25); Student.sethobby (Newstring[]{"basketball", "surfing the Internet", "Running", "games"}); /*** Java objects are converted to JSON objects and get JSON object properties*/Jsonobject Jsonstu=Jsonobject.fromobject (student); System.out.println (Jsonstu.tostring ()); System.out.println (Jsonstu.getjsonarray ("Hobby")); /*** JSON objects are converted to Java objects and get Java object Properties*/Student Stu= (Student) Jsonobject.tobean (Jsonstu, Student.class); System.out.println (Stu.getname ()); /*** Create JSON object*/Jsonobject jsonobj=NewJsonobject (); Jsonobj.put ("id", 1); Jsonobj.put ("Name", "Zhang Yong"); Jsonobj.put ("Sex", "male"); //jsonobj.put ("Age", 24); //jsonobj.put ("hobby", New string[]{"Internet", "games", "Running", "Music"}); //System.out.println (jsonobj.tostring ()); /*** JSON objects are converted to Java objects*/Student Stud= (Student) Jsonobject.tobean (jsonobj,student.class); System.out.println (Stud.getage ()); }}
View Code
Run results
{"Age": "Hobby": ["basketball", "internet", "Run", "game"], "id": 1, "name": "Jag", "Sex": "Man"}["basketball", "internet", "Run", "Game"]jag 0
Change the code.
New Jsonobject (); Jsonobj.put ("id", 1); Jsonobj.put ("name", "Zhang Yong"); Jsonobj.put ("old", "male"); // This is an element that the class does not have
Results
{"Age": "Hobby": ["basketball", "internet", "Run", "game"], "id": 1, "name": "Jag", "Sex": "Man"}["basketball", "internet", "Run", "Game"]jag 05:18:22class Student
Student class
Importjava.io.Serializable; Public classStudentImplementsSerializable {Private LongID; PrivateString name; PrivateString sex; Private intAge ; Privatestring[] hobby; Public LonggetId () {returnID; } Public voidSetId (LongID) { This. ID =ID; } PublicString GetName () {returnname; } Public voidsetName (String name) { This. Name =name; } PublicString Getsex () {returnsex; } Public voidsetsex (String sex) { This. Sex =sex; } Public intGetage () {returnAge ; } Public voidSetage (intAge ) { This. Age =Age ; } Publicstring[] Gethobby () {returnHobby; } Public voidsethobby (string[] hobby) { This. Hobby =Hobby; } }
View Code
JSON into objects