Use in the Json--java

Source: Internet
Author: User

1. Building the JSON method (data-->json)

Use MAVEN to build your project here

Add the following dependencies in the Pom.xml

 <Dependency>      <groupId>Org.json</groupId>      <Artifactid>Json</Artifactid>      <version>20090211</version>    </Dependency>

1.1 Create Jsonobject object, use put (Key,value) assignment, toString () print out JSON format

Keywords: jsonobject object, put (), toString ()

 Public classJsonobjectsimple { Public Static voidMain (string[] args) {jsonobjectsimple (); }        Private Static voidjsonobjectsimple () {jsonobject Xiaofeng=NewJsonobject (); Object Nullobj=NULL;//because of the put () method, NULL is not directly used here, so null objects are created to skip the compiler's check        Try{xiaofeng.put ("Name", "Xiao Feng"); Xiaofeng.put ("Age", 22); Xiaofeng.put ("Birthday", "1999-11-22"); Xiaofeng.put ("School", "Qinghua University"); Xiaofeng.put ("Major",NewString[] {"Sing", "coding"}); Xiaofeng.put ("Girlfriend", "true"); Xiaofeng.put ("Car", nullobj);//You cannot use NULL directly, you need to create a null object to skip the compiler's checkXiaofeng.put ("comment", "JSON cannot use annotations directly, you need to add this way: "); } Catch(jsonexception e) {//TODO auto-generated Catch blockE.printstacktrace ();         } System.out.println (Xiaofeng.tostring ()); }   }

Copy the console output to http://www.jsoneditoronline.org/to view the JSON data structure

1.2 Build with HashMap

Key words: HashMap (), put (), toString (), Jsonobject (Xiaofeng)

Private Static voidCreatejsonbymap () {Map<String,Object> xiaofeng=NewHashmap<string,object>(); Object Nullobj=NULL; Xiaofeng.put ("Name", "Xiao Feng"); Xiaofeng.put ("Age", 22); Xiaofeng.put ("Birthday", "1999-11-22"); Xiaofeng.put ("School", "Qinghua University"); Xiaofeng.put ("Major",NewString[] {"Sing", "coding"}); Xiaofeng.put ("Girlfriend", "true"); Xiaofeng.put ("Car", nullobj);//You cannot use NULL directly, you need to create a null object to skip the compiler's checkXiaofeng.put ("comment", "JSON cannot use annotations directly, you need to add this way: "); System.out.println (NewJsonobject (Xiaofeng). toString ()); }

3. Create JSON using JavaBean

Key words: JavaBean, setxxx (), Jsonobject (Xiaofeng)

First create the JavaBean class person (slightly), and then create ...

 private  static  void   Createjsonbybean () { // Span style= "color: #008000;" > Create the person object, assign a value with the set () method, and finally turn to the Jsonobject object output  person xiaofeng=new   person ();        Xiaofeng.setname ( "Xiao Feng" );        Xiaofeng.setage ( 22.5);        Xiaofeng.setgirlfriend ( true  ); Xiaofeng.setmajor ( new  string[]{"Sing", "coding"                }); System.out.println ( new   Jsonobject (                Xiaofeng)); }

Note that when you create JavaBean, because JSON does not support date format, the date format needs to be set to string type, which is also a drawback of JSON.

2. Parsing read JSON data (json--> data)

Xiaofeng.json
{  "birthday": "1999-11-22",  "Girlfriend": "true",  "Major": [     "Sing",    "coding"  ],  "school": "Qinghua University",  null  ,  "name": "Xiao Feng",  "comment": "JSON cannot use annotations directly, you need to add this way." ",  " age ":

Reading JSON from a file

Keywords:

ReadJSON.class.getResource ("/xiaofeng.json"). GetFile (), jsonarray,readfiletostring (file)

Public class Readjson {public staticvoidMain (string[] args) throws IOException, jsonexception {//get the JSON file under this file pathFile file=NewFile (ReadJSON.class.getResource ("/xiaofeng.json"). GetFile ()); //read JSON file contentsString content=fileutils.readfiletostring (file); Jsonobject Jsonobject=Newjsonobject (content);
System.out.println ("Name is:" +jsonobject.getstring ("name")); System.out.println ("Age is:" +jsonobject.getdouble ("ages"))); System.out.println ("Do you have a girlfriend?" +jsonobject.getboolean ("Girlfriend"));
//array type is converted to Jsonarray type to parse and cannot be read directly Jsonarray Majorarray=jsonobject.getjsonarray ("Major"); for(intI=0;i<majorarray.length (); i++) {String m=(String) majorarray.get (i); System.out.println ("Professional--" + (i+1) +m); } } }

Console output

              

To increase the robustness of the program, you can add non-null "isNull ()" judgment when JSON data is parsed

// determine if name is empty        if (!jsonobject.isnull ("name")) {            System.out.println ("name is:" + jsonobject.getstring ("name"));        }         // Counter example, no output        if (!jsonobject.isnull ("NME")) {            System.out.println ("name is:" + jsonobject.getstring ("name"));        }        System.out.println ("Age is:" + jsonobject.getdouble ("ages"));

Use in the Json--java

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.