JAVA & JSON detailed

Source: Internet
Author: User

JSON definition

JSON (JavaScript Object Notation) is a lightweight data interchange format. It is based on a subset of ECMAScript. JSON takes a completely language-independent text format, but also uses a similar idiom to the C language family (c, C + +, C #, Java, JavaScript, Perl, Python, and so on). These features make JSON an ideal data exchange language. Easy to read and write, but also easy to machine parse and generate (network transfer rate).

JSON use
    • Use JavaScript-based applications, including browser extensions and Web sites

    • Serialized and structured data transfer Network connection using JSON format

    • This is primarily used for data transfer between servers and Web applications

    • Web services and APIs provide common data in JSON format

    • It can be used with modern programming languages

Features of JSON
    • Easy to read and write JSON

    • Lightweight text-based interchange format

    • Independent language

JSON Syntax RulesThe JSON syntax is a subset of the JavaScript object representation syntax.
    • Data in key-value pairs
    • Data is separated by commas
    • Curly braces Save Object
    • Square brackets Save Array
JSON name/value pairsThe writing format for JSON data is: name/value pairs. Names in name/value pairs are written in front (in double quotes), value pairs are written behind (also in double quotes), separated by colons:
{"FirstName": "Brett", "LastName": "McLaughlin", "email": "AAAA"}
The JSON format supports the following data types:
type Description
Number Double-precision floating-point format in JavaScript
String Backslash-escaped Unicode for double quotes
Boolean True or False
Array Ordered sequence of values
Value It can be a string, a number, true or False (True/false), empty (null), etc.
Object Unordered collection key-value pairs
Whitespace You can use any of the tokens in a pair
Null Empty

The following turn from: Yi Hundred Tutorial Network

Mapping between JSON and Java entities

The Json.simple entity mappings are decoded or parsed from the left to the right, and the mapped entities are encoded from right to left.

JSON Java
String Java.lang.String
Number Java.lang.Number
True|false Ava.lang.Boolean
Null Null
Array Java.util.List
Object Java.util.Map

Although decoding, the specific class of the default java.util.List is the concrete class Org.json.simple.JSONArray and the default Java.util.Map is Org.json.simple.JSONObject.

The following is a simple example to encode the jsonobject of a subclass of JSON object using Java Java.util.HashMap unordered. If you need strict order elements use the method jsonvalue.tojsonstring (map) to implement an ordered map as Java.util.LinkedHashMap and so on.

Import Org.json.simple.jsonobject;class Jsonencodedemo {public   static void Main (string[] args)    {      Jsonobject obj = new Jsonobject ();      Obj.put ("name", "foo");      Obj.put ("num", new Integer);      Obj.put ("Balance", New Double (1000.21));      Obj.put ("Is_vip", New Boolean (true));      System.out.print (obj);}   }

  

Although the above program is compiled and executed, this will produce the following results:

{"Balance": 1000.21, "num": +, "IS_VIP": True, "name": "foo"}

Here is another example, which shows the JSON object flow using Java's jsonobject:

Import Org.json.simple.jsonobject;class Jsonencodedemo {public   static void Main (string[] args)    {      Jsonobject obj = new Jsonobject ();      Obj.put ("name", "foo");      Obj.put ("num", new Integer);      Obj.put ("Balance", New Double (1000.21));      Obj.put ("Is_vip", New Boolean (true));      StringWriter out = new StringWriter ();      Obj.writejsonstring (out);            String Jsontext = out.tostring ();      System.out.print (Jsontext);   }}

Although the above program is compiled and executed, this will produce the following results:

{"Balance": 1000.21, "num": +, "IS_VIP": True, "name": "foo"}
JSON decoding in Java

The following example takes advantage of the Jsonobject and Jsonarray Jsonobject is a java.util.Map Jsonarray is a java.util.List, so it can be accessed by the standard operation of the Map and List.

Import Org.json.simple.jsonobject;import Org.json.simple.jsonarray;import org.json.simple.parser.ParseException; Import Org.json.simple.parser.jsonparser;class Jsondecodedemo {public static void main (string[] args) {Jsonpar      Ser parser=new jsonparser ();      String s = "[0,{\" 1\ ": {\" 2\ ": {\" 3\ ": {\" 4\ ": [5,{\" 6\ ": 7}]}}}]";         try{Object obj = Parser.parse (s);         Jsonarray array = (jsonarray) obj;         System.out.println ("The 2nd element of array");         System.out.println (Array.get (1));         System.out.println ();         Jsonobject obj2 = (jsonobject) array.get (1);         System.out.println ("Field \" 1\ "");             System.out.println (Obj2.get ("1"));         s = "{}";         obj = Parser.parse (s);         System.out.println (obj);         S= "[5,]";         obj = Parser.parse (s);         System.out.println (obj);         S= "[5,,2]";         obj = Parser.parse (s);      System.out.println (obj); }catch (parseexception pe) {System.out.println("Position:" + pe.getposition ());      SYSTEM.OUT.PRINTLN (PE); }   }}

Although the above program is compiled and executed, this will produce the following results:

The 2nd element of array{"1": {"2": {"3": {"4": [5,{"6": 7}]}}}}field "1" {"2": {"3": {"4": [5,{"6": 7}]}}}{}[5][5,2]

JAVA & JSON detailed

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.