Java-json Series (ii): Parsing and processing JSON data with Jsonobject

Source: Internet
Author: User

This article mainly introduces some common scenarios and methods of jsonobject processing JSON data.

(i) Jar package download

Required jar package download Baidu network address: Https://pan.baidu.com/s/1c27Uyre

(ii) Common scenarios and treatment methods

1. Parse a simple JSON string:

1 // a simple JSON test string 2          Public Static Final String json_simple = "{' name ': ' Tom ', ' Age ': +}"; 3         4         Jsonobject obj = jsonobject.fromobject (json_simple); 5         System.out.println ("name is:" + obj.get ("name")); 6         System.out.println ("Age was:" + obj.get ("age"));

Output:

Name Is:tom
Age Is:16

2. Parsing nested JSON strings:

1       //Nested JSON strings2          Public Static FinalString Json_multi = "{' name ': ' Tom ', ' score ': {' Math ': 98, ' 中文版 ': 90}}";3Jsonobject obj =Jsonobject.fromobject (json_multi);4System.out.println ("name is:" + obj.get ("name"));5System.out.println ("score is:" + obj.get ("Score"));6 7Jsonobject scoreobj = (jsonobject) obj.get ("Score");8System.out.println ("Math score is:" + scoreobj.get ("math"));9System.out.println ("中文版 score is:" + scoreobj.get ("中文版"));

Output:

Name Is:tom
Score is: {"中文版": +, "Math": 98}
Math score Is:98
中文版 score Is:90

3. Transform the Bean object into a Jsonobject object:

The person, Info, and score classes are as follows: (note: To be defined as a separate three public class, it cannot be defined as an inner or non-public class, otherwise the exception will be converted)

1  Public classPerson {2     PrivateString name;3 4     Privateinfo info;5 6      PublicString GetName () {7         returnname;8     }9 Ten      Public voidsetName (String name) { One          This. Name =name; A     } -  -      PublicInfo GetInfo () { the         returninfo; -     } -  -      Public voidSetInfo (Info info) { +          This. info =info; -     } +  A @Override at      PublicString toString () { -         return"Person [name=" + name + ", info=" + info + "]"; -     } -  -}
1  Public classInfo {2     Private intAge ;3     Privatescore score;4 5      Public intGetage () {6         returnAge ;7     }8 9      Public voidSetage (intAge ) {Ten          This. Age =Age ; One     } A  -      Publicscore Getscore () { -         returnscore; the     } -  -      Public voidSetScore (Score score) { -          This. score =score; +     } -  + @Override A      PublicString toString () { at         return"Info [age=" + Age + ", score=" + score + "]"; -     } -  -}
1  Public classScore {2     PrivateString Math;3     PrivateString 中文版;4 5      PublicString Getmath () {6         returnMath;7     }8 9      Public voidSetmath (String math) {Ten          This. Math =Math; One     } A  -      PublicString getenglish () { -         return中文版; the     } -  -      Public voidsetenglish (String 中文版) { -          This. 中文版 =中文版; +     } -  + @Override A      PublicString toString () { at         return"Score [math=" + Math + ", english=" + 中文版 + "]"; -     } -  -}

Conversion method:

1Score score =Newscore ();2Score.setenglish ("A");3Score.setmath ("B");4 5Info info =NewInfo ();6Info.setage (20);7 Info.setscore (score);8 9Person person =NewPerson ();Ten Person.setinfo (info); OnePerson.setname ("Tim"); A  -Jsonobject obj =Jsonobject.fromobject (person); -System.out.println (Obj.tostring ());

Output:

{
"Name": "Tim",
"Info": {
"Score": {
"中文版": "A",
"Math": "B"
},
"Age": 20
}
}

4. Convert the JSON array into an Jsonobject array:

1         //json in array form2          Public Static FinalString Json_array = "[{' Name ': ' Tom '},{' name ': ' John ', ' Age ': 20},{}]";3 4Jsonarray arr =Jsonarray.fromobject (json_array);5 System.out.println (arr);6 7          for(inti = 0; I < arr.size (); i++) {8Jsonobject obj =Arr.getjsonobject (i);9 System.out.println (obj.tostring ());Ten}

Output:

[{"Name": "Tom"},{"name": "John", "Age": 20},{}]
{"Name": "Tom"}
{"Name": "John", "Age": 20}
{}

5. Construct a JSON string:

1Jsonobject obj =NewJsonobject ();2Obj.put ("name", "Tom");3Obj.put ("Age", 19);4 5         //Child Objects6Jsonobject objcontact =NewJsonobject ();7Objcontact.put ("tel", "123456");8Objcontact.put ("Email", "[email protected]");9Obj.put ("Contact", objcontact);Ten  One         //sub-Array Object AJsonarray Scorearr =NewJsonarray (); -Jsonobject Objenglish =NewJsonobject (); -Objenglish.put ("Course", "中文版"); theObjenglish.put ("Result", 100); -Objenglish.put ("Level", "A"); -  -Jsonobject Objmath =NewJsonobject (); +Objmath.put ("Course", "math"); -Objmath.put ("Result", 50); +Objmath.put ("Level", "D"); A  at Scorearr.add (objenglish); - Scorearr.add (objmath); -  -Obj.put ("Score", Scorearr); -  -System.out.println (Obj.tostring ());

Output:

{
"Score": [
{
"Result": 100,
"Level": "A",
"Course": "中文版"
},
{
"Result": 50,
"Level": "D",
"Course": "Math"
}
],
"Contact": {
"Tel": "123456",
"Email": "[email protected]"
},
"Name": "Tom",
"Age": 19
}

Think: Is there a way to set the order of the fields in the output JSON?

Java-json Series (ii): Parsing and processing JSON data with Jsonobject

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.