Multiple layers of nested JSON data

Source: Internet
Author: User

Most of the time we see JSON data nested in multiple layers, like this:

{"name":"Orange Mulberry",  "Sex":"male",  " Age": -,"Grade":{"Gname":"three years and eight classes",         "Gdesc":"third day grade eight class"         }  }

To get the JSON data of the above type, it is the following steps:

1. Database queries

Sql:select S.name,s.sex,s.age,g.gname,g.gdesc

From Student S,grade g

where s.gid = G.gid; (You can also choose to use the internal connection method to write)

So we can find the information we want, and obviously the query result is a object[] collection.

2. New JavaBean

In fact, the development tool will automatically generate Java entity class student based on the relationship between multiple tables in the database.

However, most of the time a partial field query, if the query results are transferred directly to the existing JavaBean,

The non-queried property appears as 0, [] so I think it's necessary to create a new JavaBean class based on the query field.

For the above query, create the following two JavaBean:

// ostudent class member variables Private String name; Private String sex; Private String age; Private Ograde grade; // Ograde class member variables Private String Gname; Private String Gdesc;

3. Conversion of query Results

List<object[]> Listdb =query.list (); List<Ostudent> listout =NewArrayList (); for(object[]Object: Listdb) {String name= (String)Object[0]; String Sex= (String)Object[1]; String Age= (String)Object[2]; String Gname= (String)Object[3]; String Gdesc= (String)Object[4]; Ograde GRA=NewOgrade (GNAME,GDESC); Ostudent Stu=Newostudent (Name,sex,age,gra); Listout.add (stu);}

The query result is then transformed into a collection of N ostudent objects.

4. Response data

Because it is a collection of Ostudent objects, we can use the following statement to convert it to a JSON string

Jsonarray array == array.tostring (); Response.getwriter (). print (JSONSTR);

This responds to the query results in the form of multiple layers of nested JSON data.

5. Front-end invocation

After the front-end Ajax request succeeds, the data is obtained, which we can write in the callback function of the request success:

var json = $.parsejson (data); $.each (JSON, function (index, item) {           var name = json[in Dex].name;            var age = json[index].age;         var gname = json[index].grade.gname;     });

Isn't it simple?

6. Background calls

Here refer to a comment on the internet is written in full, modified, and then recorded

 Public Staticstring Getjson (string path, string parameter, string method) {Try{URL URL=NewURL (path); PrintWriter out=NULL;            String Line; StringBuilder SB=NewStringBuilder (); //opening and linking between URLsHttpURLConnection conn =(HttpURLConnection) url.openconnection (); //Request MethodConn.setrequestmethod (method); // //to set common request propertiesConn.setrequestproperty ("Accept","*/*"); Conn.setrequestproperty ("Connection","keep-alive"); Conn.setrequestproperty ("user-agent",                    "mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1)"); //Sets whether to output to httpurlconnection, sets whether to read from HttpURLConnection, and also sends a POST request to set these two//The most common HTTP requests are just get and post,get requests to get static pages, or you can put parameters behind URL strings and pass them on to the servlet.//The difference between post and get is that the post parameter is not placed inside the URL string, but is placed inside the body of the HTTP request. Conn.setdooutput (true); Conn.setdoinput (true); //gets the output stream corresponding to the URLConnection object             out=NewPrintWriter (Conn.getoutputstream ()); //send request parameters i.e. data             out. Print (parameter); //Buffered Data             out. Flush (); //gets the input stream corresponding to the URLConnection objectInputStream is=Conn.getinputstream (); //constructs a character stream cacheBufferedReader br =NewBufferedReader (NewInputStreamReader ( is));  while(line = Br.readline ())! =NULL) {sb.append (line); }            //Close the stream             is. Close (); //disconnect, preferably written on, disconnect is cut off when the underlying TCP socket link is idle.            It is not cut off if it is being used by another thread. //fixed multi-threaded words, if not disconnect, the link will increase, until the message is not sent out. Write the disconnect after the normal some. Conn.disconnect (); String Str=sb.tostring (); returnstr; } Catch(Exception e) {e.printstacktrace (); return "Something went wrong."; }    }

Call the method, get the JSON string, and the next step is to convert the JSON string into a Java object.

        String jsonstr = getjson (path, param, method);        System.  out . println (JSONSTR);         = Jsonarray.fromobject (jsonstr);         = Jsonarray. Get (0);         = Jsonobject.fromobject (o);         = (Student) Jsonobject.tobean (Jsonobject, Student.  Class);        System. out. println (Stu.getgrade ());

Because a lot of the records are usually queried, the JSON string is the form of a collection of multiple objects (arrays),

So first the JSON string---> into a JSON array---> Get array items (objects)---> Convert to JSON object---> Convert to the corresponding JavaBean object.

Then how to get the value of the member variable is not much verbose.

Multiple layers of nested 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.