Json for Java API Learning

Source: Internet
Author: User

Json for Java API Learning
First, declare:This article is a blog of many netizens. by referring to their blog, I have roughly understood some common Json in java classes and methods in projects, as well as my personal understanding of json.My personal understanding of json

In recent studies, I have read a lot of materials and learned some basic knowledge about json. Here is a simple summary:
What is json?
No. json (JavaScript Object Notation) is a simple data exchange format. Before that, I did not know that this is actually not as abstract as I thought, the following examples will be clearer.
Data Structure in json
Json only has two basic data structures: MAP, object, and Array.
1. Map
Similar to the Map in java, here we start with {and end with}. The content of the internal object is the situation of key-value pairs, which are separated by signs, different objects are separated by commas, for example: {name: hujie, age: 21} official illustration :( http://www.json.org /)


2. Array
This is similar to an array, so json is often called a json array. Here we end with [starting with]. The values in the middle are separated by commas, for example: [value1, value2, value3]
The official illustration is:


The value in the json array can be a value of many data types.


Here, the string, number, and so on do not need to be explained. Who is the truth? I can understand the specific timing, but I cannot explain it.
Knowledge point:
1. json is not hard to understand. Simply put, json is a data exchange format.
2. json has only two structures. One is object and the other is array. The two can be nested with each other. {} is an object and [] is an array.
Conversion between json and JavaScript
There is a dynamic script execution function in javaScript: eval (), which is a global javaScript Object. The eval () function can only accept the original string as a parameter. If it is not a string, it will be returned as is, otherwise, the calculation result of the string is returned (if there is a result, no result is returned) eval () case:
<Script language = javascript type = text/javascript> alert (eval (x = 10; y = 10; x * y;); // 100, execute alert (eval (2 + 3) as a js script; // 5 alert (eval (x + 10); // 20 var str = {}; // alert (eval ('+ str +') When no attribute exists in curly brackets); // The [object Object] alert (eval (str) dialog box is displayed )); // pop-up: undefinedstr = {name: 'Hj '}; // The curly braces contain an attribute alert (typeof eval (' + str + ')')); // pop-up: object, return alert (eval (str) as an object; // pop-up: hjalert (eval ('+ str + ')'). name); // pop-up: hjalert (eval (str ). name); // pop-up: undefinedstr = {name: 'Hj ', age: 21 }; // alert (eval ('+ str +') when multiple attributes exist in curly brackets ')')); // object alert (eval ('+ str + ')'). name); // hjalert (eval ('+ str + ')'). age); // 21 // alert (eval (str); // an error occurs during running, when multiple attributes are run without parentheses, an error // curly braces {} is used to declare an object. to reference this object, we must add, because the declaration statement can only be executed and cannot be returned // The purpose of being included in () is to convert the declaration statement into an expression, so that the value of the expression can be calculated, and return </script>
Note that the generated variables in the script executed by eval belong to the scope that calls eval.
<Script language = javascript type = text/javascript> eval (var str = 'global';); function test () {eval (var str = 'local ';); alert (str); // local} test (); alert (str); // global </script>
The following describes how to convert json strings and javaScript objects into javaScript objects:

<script language=javascript type=text/javascript>    var jsonpeople = [{'name':'hj','age':21},{'name':'darkrake','age':21}];var jspeople = eval('('+jsonpeople+')');alert(jspeople[0].name+:+jspeople[0].age);alert(jspeople[1].name+:+jspeople[1].age);</script>
Comparison of json and XML formats

Simple comparison:

XML:

 

      
       
    
     hj
            21    
       
       
    
     darkrake
            21    
   
  

Json string format:

 

 

{peoples:{people:[{'name':'hj','age':21},{'name':'darkrake','age':21}]}}
Here is a little more complex, multi-layer nesting:

 

 

      
   
    
Anhui Province
       
           
    
     
Lu'an
                
    
     
Jin 'an district
                
    
     
Shucheng
            
           
           
    
     
Hefei
                
    
     
Feidong
                
    
     
Feixi
            
   
      
      
   
    
Beijing
       
           
    
     
Beijing
                
    
     
Dongcheng District
                
    
     
Haidian District
            
       
  

{Address: {Province: [{ProvinceName: Anhui, City: [{CityName: lu'an, town: [Jin 'an district, Shucheng]}, {CityName: Hefei, town: [feidong, feixi]}] },{ ProvinceName: Beijing, City: {CityName: Beijing, town: [Dongcheng District, Haidian District] }}}

 

Common classes and methods of json in Java APIs
JSONObject class (usually used in combination with JSONArray)
Case:
Package javaJsonAPI; import org. json. JSONObject; public class JsonArrayTest {/** indicates that I have not found the jsonjarpackage on the official website http://www.json.org/. here, my solution is to download the source file provided on the official website *. in java *, a project named org. the json package imports all the source files. In fact, it is no different from importing the jar package in classpath */public static void main (String args []) {JSONObject jsonObject = new JSONObject ({'name': 'darkrake', 'age': 21}); System. out. println (jsonObject. get (name); System. out. println (jsonObject. get (age ));}}

JSONArray case:
Package javaJsonAPI; import org. json. JSONArray; public class JsonArrayTest {/** indicates that I have not found the jsonjarpackage on the official website http://www.json.org/. here, my solution is to download the source file provided on the official website *. in java *, a project named org. the json package imports all the source files. In fact, it is no different from importing the jar package in classpath */public static void main (String args []) {String strs [] = {one, two, three}; JSONArray myjson = new JSONArray (strs); for (int I = 0; I <myjson. length (); I ++) {System. out. println (myjson. getString (I ));}}}
Advanced: Use JSONObject in combination with the JSONArray class
Package javaJsonAPI; import org. json. JSONObject; public class JsonArrayTest {/** indicates that I have not found the jsonjarpackage on the official website http://www.json.org/. here, my solution is to download the source file provided on the official website *. in java *, a project named org. json package, which imports all the source files, is actually no different from importing the jar package in classpath */public static void main (String args []) {String str = {address: {Province: {ProvinceName: Anhui, City: [{CityName: lu'an, own: [Jin 'an district, Shu Cheng]}, {CityName: Hefei, own: [feidong, feixi]}] }}; JSONObject jo = new JSONObject (str); String ProvinceName = jo. getJSONObject (address )//. getJSONObject (Province ). get (ProvinceName ). toString (); // System. out. println (ProvinceName); String cityName = jo. getJSONObject (address ). getJSONObject (Province )//. getJSONArray (City ). getJSONObject (0 ). get (CityName )//. toString (); System. out. println (+ cityName); String town1 = jo. getJSONObject (address ). getJSONObject (Province )//. getJSONArray (City ). getJSONObject (0 ). getJSONArray (town )//. get (0 ). toString (); System. out. println (+ town1); String town2 = jo. getJSONObject (address ). getJSONObject (Province )//. getJSONArray (City ). getJSONObject (0 ). getJSONArray (town )//. get (1 ). toString (); System. out. println (+ town2 );}}
JSONStringer
-> Quickly construct a JSON string and write it to the file.
Basic Methods:

JSONStringer is a subclass of JSONWriter;

JSONStringer is constructed by object (). key (). value (). key (). value (). endObject;

JSONString (): Constructor

Object () indicates to start an object, that is, add {;

EndObject () indicates that an object is ended, that is, adding };

Array () indicates to start an array, that is, to add [;

EndArray () indicates to end an array, that is, to add a];

Key () indicates adding a key;

Value () indicates adding a value;

Note: Through this method, "," between objects and "," between values of Array arrays are automatically added.

Simple case:

 

Package javaJsonAPI; import org. json. JSONStringer; public class JsonArrayTest {/** indicates that I have not found the jsonjarpackage on the official website http://www.json.org/. here, my solution is to download the source file provided on the official website *. in java *, a project named org. the json package imports all the source files. In fact, it is no different from importing the jar package in classpath */public static void main (String args []) {JSONStringer js = new JSONStringer (); js. array (); js. object (); js. key (name); js. value (hj); js. key (age); js. value (21); js. endObject (); js. object (); js. key (name); js. value (darkrake); js. key (age); js. value (21); js. endObject (); js. endArray (); System. out. println (js. toString ());}}

Small Comprehensive case:

 

 

Package javaJsonAPI; import org. json. JSONArray; import org. json. JSONObject; import org. json. JSONStringer; public class JsonArrayTest {/** indicates that I have not found the jsonjarpackage on the official website http://www.json.org/. here, my solution is to download the source file provided on the official website *. in java *, a project named org. the json package imports all the source files. In fact, it is no different from importing the jar package in classpath */public static void main (String args []) {JSONStringer js = new JSONStringer (); // create book1JSONObject book1 = new JSONObject (); book1.put (name, Java); JSONArray ja1 = new JSONArray (); string str1 [] = {LiuWANJUN, XXX}; ja1.put (str1); book1.put (author, ja1); book1.put (price, ¥108 ); // create book2JSONObject book2 = new JSONObject (); book2.put (name, JavaScript); JSONArray ja2 = new JSONArray (); String str2 [] = {LiSongFeng, CaoLi }; ja2.put (str2); book2.put (author, ja2); book2.put (price, ¥108); js. object (); js. key (Book); js. array (); js. value (book1); js. value (book2); js. endArray (); js. endObject (); System. out. println (js. toString ());}}
{  Book: [    {      author: [        [          LiuWANJUN,          XXX        ]      ],      price: ¥108,      name: Java    },    {      author: [        [          LiSongFeng,          CaoLi        ]      ],      price: ¥108,      name: JavaScript    }  ]}
Convert to XML:

 

 

  
   LiuWANJUNXXX
   
    ¥108
   
   
    Java
   
  
  
   LiSongFengCaoLi
   
    ¥108
   
   
    JavaScript
   
  

 

Summary:
1. JSON is a data exchange format, which is widely used in web projects. In particular, AJAX loads data in one step, usually in json format, rather than traditional XML;
2. JSON has only two structures: Object and Array.
3. I don't know if I wrote anything wrong. I also learned and understood it based on others' learning schemes. I will have time next week to study the JSON application in the previous section, here, we mainly write operations on the Java background.
 

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.