JSON data interface provided by the server and client-side receive parsing JSON data

Source: Internet
Author: User

JSON-formatted service interface: http://www.cnblogs.com/visec479/articles/4118338.html

First to understand the JSON format parsing

The format of a JSON structure is a collection of key/value pairs (key, value) that can be understood as a dictionary (Dictionary), and each key/value pair can be understood as an object. A key (key) in a key/value pair is typically a string, a value (a string, a double, an int, and so on), or a key/value pair, or an array, where the type of data inside the array can be a basic type, or a key/value pair. You can see that the key/value is nothing, just nested a lot of it will feel confused, here is a concrete example to illustrate. Note: This code is for illustrative purposes only and does not work correctly.

1 var testjson = {
2 "Name": "Obama",
3 "byname": ["Xiao Ao", "minibus", "Pony"],
4 "Education": {
5 "Gradeschool": "First primary school in Washington",
6 "Middleschool": ["The first junior high school in Washington", "the First of Washington"],
7 "University": {
8 "Name": "Harvard University",
9 "Specialty": ["Software Engineering", "Accounting"]
Ten}
One }
-- }

The variable Testjson is a JSON object, and the Testjson object consists of three key/value pairs.

The first key/value pair: Key (key) is "name" and its corresponding value is "Obama", i.e. testjson["name"] = = "Obama"

The second key/value pair: The key is "byname" and the value is an array, which is a string collection. If necessary, the elements inside the array can also be key/value pairs.

The third key/value pair: The key is "education", the value is a JSON pair, the JSON object includes three key/value pairs, which is nested ...

Summary: A JSON object is a collection of key/value pairs, a string, a value that is a primitive type, or a nested JSON object, or an array (the elements in the array can be basic types, or they can be JSON objects that can continue nesting).

Get Name: testjson["Name"]

Gets the first alias: testjson["ByName"][0]. The value of the Testjson key "ByName" is a string array

Access to primary School name: testjson["Education" ["Gradeschool"], University Major: Testjson["Education" ["University"] [specialty]][0]

Here's an example:

Define a string that conforms to the JSON format requirements:

String Testjson = "{\" name\ ": \" Obama \ ", \" byname\ ": [\" Xiao ao \ ", \" minibus \ "," Pony ""],\ "education\": {\ "gradeschool\": \ "Washington first primary school \" , \ "middleschool\": [\ "Washington first high school \", "Washington first high school \"], \ "university\": {\ "name\": \ "Harvard University \", \ "specialty\": [\ "Software engineering \", \ "Accounting \"]} }}";

You then need to use the string as a parameter to the new Jsonobject object. Microsoft comes with the class library System.json, and then adds namespaces using System.json;

The main code is one sentence: Jsonobject js = Jsonobject.parse (Testjson); Use the string Testjson as a parameter to the new Jsonobject object. By monitoring we can see the contents of JS and the same as expected, through the following picture you should be able to figure out a lot of things to

Additional sentence: js["Education" ["University"] ["specialty"] content is {["Software engineering", "Accounting"]},

But js["Education" ["University"] ["specialty"]. The value of Contains ("Software Engineering") is false. Reason Oneself pondering

Creating server-side JSON data from a servlet

The server provides a JSON data interface: Http://192.168.0.129:8080/JSONInterface/JsonServlet

Package Jsonmanager;Importjava.io.IOException;ImportJava.io.PrintWriter;ImportJava.util.HashMap;ImportJava.util.Map;Importjavax.servlet.ServletException;ImportJavax.servlet.http.HttpServlet;Importjavax.servlet.http.HttpServletRequest;ImportJavax.servlet.http.HttpServletResponse;ImportNet.sf.json.JSONObject;/** * Jsonobject Create a JSON object and Out.write (); * @author Dana Li*/ Public classJsonservletextendsHttpServlet {Private StaticFinal long Serialversionuid =1L;  Public voiddoget (httpservletrequest request, httpservletresponse response) throws Servletexception, IOException {  This. DoPost (request, response); } @SuppressWarnings ({"Rawtypes","Unchecked" })     Public voidDoPost (httpservletrequest request, httpservletresponse response) throws Servletexception, IOException { Response.setcontenttype ("Text/html"); Response.setcharacterencoding ("UTF-8");//solve Chinese garbled problemPrintWriter out=Response.getwriter (); Map Map=NewHashMap (); Map.put ("Name","Dana, Li"); Map.put ("Age",NewInteger (22)); Map.put ("Provinces",NewString ("Guangdong province")); Map.put ("Citiy",NewString ("Zhuhai")); Map.put ("Master",NewString ("C, C + +, Linux, Java")); Jsonobject JSON=jsonobject.fromobject (map);        Out.write (Json.tostring ());        Out.flush ();    Out.close (); }}

Turn on the service to see if it's turned on ~

The client invokes the interface to parse the JSON data

ImportJava.io.BufferedReader;Importjava.io.IOException;ImportJava.io.InputStreamReader;ImportJava.net.URL;Importjava.net.URLConnection;/** * Receive server JSON data * @author Dana Li*/ Public classgetjsoninterfaceinfo{Private StaticString urlpath="Http://192.168.0.129:8080/JSONInterface/JsonServlet"; /** * @param args * @throws ioexception*/     Public Static voidMain (string[] args) throws IOException {//serverfactory.getserver (8080). Start ();        //List raw DataStringBuilder JSON =NewStringBuilder (); URL Oracle=NewURL (Getjsoninterfaceinfo.urlpath); URLConnection YC=oracle.openconnection (); BufferedReaderinch=NewBufferedReader (NewInputStreamReader (Yc.getinputstream (),"UTF-8")); String Inputline=NULL;  while((Inputline =inch. ReadLine ())! =NULL) {json.append (inputline); }         inch. Close (); String Strjson=json.tostring (); System.out.println ("raw data:");     System.out.println (Strjson.tostring ()); }}

JSON format parsing goto: http://www.cnblogs.com/zouzf/archive/2012/03/31/2426646.html

JSON data interfaces provided by the server and client receive parse JSON data

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.