Json for Java API learning, jsonapi

Source: Internet
Author: User

Json for Java API learning, jsonapi
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], and 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 there is no attribute in the curly brackets); // the pop-up: [object Object] alert (eval (str); // displayed: undefinedstr = "{name: 'Hj '}"; // There is an attribute alert (typeof eval ('+ str +') in the curly brackets); // the pop-up: object, returns alert (eval (str) as an object; // 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:

<peoples>    <people>    <name>hj</name>        <age>21</age>    </people>    <people>    <name>darkrake</name>        <age>21</age>    </people></peoples>

Json string format:

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

<Address> <Province> <ProvinceName> Anhui </ProvinceName> <City> <CityName> Lu 'an </CityName> <town> Jin 'an district </town> <town> Shu Cheng </town> </City> <CityName> Hefei </CityName> <town> feidong </town> <town> Feixi </town> </City> </Province> <Province> <ProvinceName> Beijing </ProvinceName> <City> <CityName> Beijing </CityName> <town> Dongcheng District </town> <town> Haidian District </town>/ city> </Province> </address>

{"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. 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 str = "{\" address \ ": {\" Province \ ": {\" ProvinceName \ ": \" Anhui \ ", \" City \": [{\ "CityName \": \ "Lu 'an \", \ "town \": [\ "Jin 'an district \", \ "Shu Cheng \"]}, {\ "CityName \": \ "Hefei \", \ "town \": [\ "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:

<Book><author>LiuWANJUN</author><author>XXX</author><price>¥108</price><name>Java</name></Book><Book><author>LiSongFeng</author><author>CaoLi</author><price>¥108</price><name>JavaScript</name></Book>

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.
Recommended:
Http://www.bejson.com/go.html? U = http://www.bejson.com/xml2json


How can I use java to obtain json data returned by Baidu API?

Import java. io. bufferedReader; import java. io. IOException; import java. io. inputStream; import java. io. inputStreamReader; import java. io. unsupportedEncodingException; import java.net. httpURLConnection; import java.net. malformedURLException; import java.net. URL; public class HttpRequestUtil {/*** obtain the returned String from the url request ** @ param requestUrl * @ return JSON String */public static String HttpRequest (String requestUrl) {StringBuffer sb = new StringBuffer (); InputStream ips = getInputStream (requestUrl); InputStreamReader isreader = null; try {isreader = new InputStreamReader (ips, "UTF-8 ");} catch (UnsupportedEncodingException e) {e. printStackTrace ();} BufferedReader bufferedReader = new BufferedReader (isreader); String temp = null; try {while (temp = bufferedReader. readLine ())! = Null) {sb. append (temp);} bufferedReader. close (); isreader. close (); ips. close (); ips = null;} catch (IOException e) {e. printStackTrace ();} return sb. toString ();}/*** get the returned stream data from the request URL * @ param requestUrl * @ return InputStream */private static InputStream getInputStream (String requestUrl) {URL url = null; HttpURLConnection conn = null; InputStream in = null; try {url = new URL (requestUrl);} c ...... remaining full text>

Java is used for JSON conversion. I have a jsonjar package, which should not be json2, but cannot find the corresponding json api, which is not understandable in many places.

JSONArray data is in the array format and contains multiple jsonobjects.
JSONObject is an object.
The JSONArray data format is [JSONObject, 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.