Talking about using Java to parse and generate Json_java

Source: Internet
Author: User
Tags object object

JSON overview

JSON, the JavaScript Object notation, is a subset of the JavaScript objects representation. Has the following characteristics:

The data is placed in the key value pair;
Data is separated by commas;
curly braces represent objects;
square brackets represent arrays.

The value of the JSON can be:

Number (integer or floating-point numbers)
String (in double quotes)
Logical value (TRUE or FALSE)
Array (in square brackets)
Objects (within curly braces)
Null

Basic syntax for JSON

JSON object

The JSON object is written in curly braces, and the object can contain multiple key-value pairs, such as:

{"
  firstName": "John",
  "LastName": "Doe"
}

JSON array

The JSON array is written in square brackets, and the array can contain multiple objects, such as:

{"
  employees": [
    {"FirstName": "John", "LastName": "Doe"},
    {"FirstName": "Anna", "LastName": "Smith"},
    {"FirstName": "Peter", "LastName": "Jones"}
  ]
}

In the above example, the curly braces at the root indicate that this is a JSON object whose key is employees, the value is a JSON array, there are 3 JSON objects in the array, and each JSON object is separated by commas.

Using Java to read JSON data

In the JSON website we can see the various syntax to the JSON support, for Java is more mature is google-gson.

Its maven dependencies are as follows:

<dependency>
  <groupId>com.google.code.gson</groupId>
  <artifactid>gson</ artifactid>
  <version>2.2.4</version>
</dependency>

Now write the program to parse the following test.json:

{
  "cat": "It",
  "languages": [
    {"id": 1, "IDE": "Eclipse", "name": "Java"},
    {"id": 2, "IDE": "Xcode", " Name ": Swift"},
    {"id": 3, "IDE": "Visual Studio", "name": "C #"}
  ],
  "Pop": True
}

The following code resolves the above JSON data:

public void Readjson () throws exception{

  //Create JSON parser
  jsonparser parser = new Jsonparser (); 
  Parses the JSON data using the parser, the return value is Jsonelement, and is coerced into its subclass Jsonobject type
  Jsonobject object = (jsonobject) parser.parse (new FileReader ("Test.json"));

  Returns the jsonelement using the Jsonobject get (String memebername) method, and then uses the Jsonelement Getasxxx method to obtain the True type
  System.out.println (" Cat = "+ Object.get (" Cat "). getasstring ());

  Traversal JSON array
  Jsonarray languages = Object.getasjsonarray ("languages");
  for (Jsonelement jsonelement:languages) {
    Jsonobject language = Jsonelement.getasjsonobject ();
    SYSTEM.OUT.PRINTLN ("id =" + language.get ("id"). Getasint () + ", ide =" + language.get ("IDE"). Getasstring () + ", name =" + Language.get ("name"). getasstring ());

  System.out.println ("pop =" + object.get ("Pop"). getasstring ());


Generating JSON data using Java

The key to

Generating JSON data is the add and AddProperty two methods in the JSON object. The former is used to add an array or another JSON object to the JSON object, which is used to add attributes to the JSON object. The following code will generate the Test.json in the example above.

public void Createjson () throws ioexception{Jsonobject object = new Jsonobject ();//Create a JSON object Object.addproperty (    "Cat", "it"); Add a property to the JSON object Jsonarray languages = new Jsonarray ();
  Create a JSON array jsonobject language = new Jsonobject ();
  Language.addproperty ("id", 1);
  Language.addproperty ("IDE", "Eclipse");
  Language.addproperty ("name", "Java");        Languages.add (language);
  Adds a JSON object to the array language = new Jsonobject ();
  Language.addproperty ("id", 2);
  Language.addproperty ("IDE", "XCode");
  Language.addproperty ("name", "Swift");

  Languages.add (language);
  Language = new Jsonobject ();
  Language.addproperty ("id", 3);
  Language.addproperty ("IDE", "Visual Studio");
  Language.addproperty ("name", "C #");

  Languages.add (language);  Object.add ("Languages", languages);

  Adds an array to the JSON object Object.addproperty ("Pop", true);  String jsonstr = object.tostring (); Converts a JSON object to a JSON string printwriter pw = new PrintWriter (New FileWriter ("Data.jsOn "));
  Pw.print (JSONSTR);
  Pw.flush ();
Pw.close ();
 }

To construct and parse JSON in Java I'm using Org.json, here are two functions, one is to create JSON, one is to construct JSON from text and parse it.

Create JSON

Construct JSON and output it public  
String jsontest () throws jsonexception{ 
  jsonobject json=new jsonobject (); C3/>jsonarray jsonmembers = new Jsonarray (); 
  Jsonobject member1 = new Jsonobject (); 
  Member1.put ("LoginName", "Zhangfan"); 
  Member1.put ("Password", "Userpass"); 
  Member1.put ("email", "10371443@qq.com"); 
  Member1.put ("Sign_date", "2007-06-12"); 
  Jsonmembers.put (member1); 
 
  Jsonobject member2 = new Jsonobject (); 
  Member2.put ("LoginName", "ZF"); 
  Member2.put ("Password", "Userpass"); 
  Member2.put ("email", "8223939@qq.com"); 
  Member2.put ("Sign_date", "2008-07-16"); 
  Jsonmembers.put (member2); 
  Json.put ("Users", jsonmembers); 
 
  return json.tostring (); 
} 

Parsing JSON

Construct JSON from String and resolve it. 
public string JsonTest2 () throws jsonexception{ 
  string jsonstring= "{\ users\": [{\ loginname\]: \ "zhangfan\", \ " Password\ ": \ userpass\", "email\": \ "10371443@qq.com\"},{\ "loginname\": \ "zf\", \ "password\": \ "userpass\", "email \ ": \" 822393@qq.com\ "}]}"; 
  Jsonobject json= New Jsonobject (jsonstring); 
  Jsonarray Jsonarray=json.getjsonarray ("users"); 
  String loginnames= "LoginName list:"; 
  for (int i=0;i<jsonarray.length (); i++) { 
    jsonobject user= (jsonobject) jsonarray.get (i); 
    String Username= (String) user.get ("LoginName"); 
    if (I==jsonarray.length ()-1) { 
      loginnames+=username 
    } else{ 
      loginnames+=username+ ","; 
    } 
  } 
  return loginnames; 
} 

Processing JSON in Java is also quite handy.

Related Article

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.