[Easy to understand] practical project development (I) parses JSON data to obtain the adapter data source, jsonadapter

Source: Internet
Author: User

[Easy to understand] practical project development (I) parses JSON data to obtain the adapter data source, jsonadapter

It does not elaborate on how the third-party control introduces the project, and does not paste the complete code. After the application is completed, it will be open-source, although there is no great value from the current perspective.

Only record the problems encountered during code writing and how to solve them.

 

There are many homogeneous applications on the market, so this is also written to train hands. Not much nonsense.

 

The subject of the application is a joke and an interesting figure. To present the joke content, a data source is required. There are basically three ways to get the data source, 1. Read from the local,

2. crawl from the network, 3. obtain from the third-party sdk interface. The first method is different from the original intention of my development. I don't want to use a single machine. The second method is currently

The level is not enough, and data crawling does not guarantee the stability of the data source. In summary, the third-party interface is the most convenient and stable.

 

Select the interface for aggregation data sdk jokes.

 

An example is provided on the official website. The json data format obtained by sending a request is as follows:

 

Below we can use the conversion tool provided by the http://www.bejson.com/json2javapojo/ to generate Json data corresponding to the POJO class for parsing,

Of course, you can also write it by yourself

We can see that the data contained in the json string is a Json array, and the smallest unit is a joke data. For example

{"Content": "The University was poor. In order to make some money to play games online, several old Wang dormitory buddies came up with a solution:" The old boss helped me write homework, and the second master helped me write compositions, the old Three write love letters, and the old Wang write reviews." Later, four of them became the famous four treasures of wenfang. "," HashId ":" ACD50D5A66C2201566CF53138901A716 "," unixtime ": 1441868049," updatetime ":" 14:54:09 "}

We will first abstract it as follows:

Public class Data {private String content; private String hashId; private Long unixtime; private String updatetime; public Data () {} public Data (String content, String hashId, Long unixtime, string updatetime) {super (); this. content = content; this. unixtime = unixtime; this. hashId = hashId; this. updatetime = updatetime;} public String getContent () {return content;} public String getUpdatetime () {Return updatetime;} public String getHashId () {return hashId;} public Long getUnixtime () {return unixtime ;}@ Override public String toString () {return "Data [content =" + content + ", unixtime =" + unixtime + ", hashId =" + hashId + ", updatetime =" + updatetime + "]";} /*** because the Update Time and unixtime are not unique * use the unique hashId to obtain the hash code */@ Override public int hashCode () {final int prime = 31; int result = 1; result = prime * result + (hashId = null )? 0: hashId. hashCode (); return result ;} /*** because the Update Time and unixtime are not unique * Here we use the unique hashId to compare */@ Override public boolean equals (Object obj) {if (this = obj) return true; if (obj = null) return false; if (getClass ()! = Obj. getClass () return false; Data other = (Data) obj; if (hashId = null) {if (other. hashId! = Null) return false;} else if (! HashId. equals (other. hashId) return false; return true ;}

 

The POJO class of Json data is as follows:

Package com. sphere. joke. entity; import java. util. list;/*** create a POJO object class corresponding to the given json String */public class Message {private int error_code; private String reason; private List <Data> result; public Message (int error_code, String reason, List <Data> result) {this. error_code = error_code; this. reason = reason; this. result = result;} public int getError_code () {return this. error_code;} public String getReason () {return this. reason;} public List <Data> getResult () {return result ;}@ Override public String toString () {return "Message [error_code =" + error_code + ", reason = "+ reason +", result = "+ result +"] ";}}

 

Our goal is to get the result as the data source for displaying the list adapter.

Okay, we have already created the POJO object. How can we parse the Json data,

The following uses the APIS provided by GSON to parse the JSON data we get,

 

Introduce gson-2.2.4.jar into the project

 

Create a new parsing class ParseJson. java

 

First, it starts from the smallest unit and starts from the inside to the outside.

 

An example of parsing a joke Data and returning Data is as follows:

/*** Parse the smallest unit in the json character * @ param reader * @ return * @ throws IOException */public Data readData (JsonReader reader) throws IOException {String content = null; string hashId = null; Long unixtime = 0L; String updatetime = null; reader. beginObject (); while (reader. hasNext () {String name = reader. nextName (); if (name. equals ("content") {// replace \ t \ s \ n \ r content = UtilsHelper. replaceBlank (reader. nextString ();} else if (name. equals ("hashId") {hashId = reader. nextString ();} else if (name. equals ("unixtime") {unixtime = reader. nextLong ();} else if (name. equals ("updatetime") {updatetime = reader. nextString ();} else {reader. skipValue () ;}} reader. endObject (); return new Data (content, hashId, unixtime, updatetime );}

 

Parse the data array as follows:

/*** Return the parsing result set of the internal json array * @ param reader * @ return * @ throws IOException */public List <Data> readDatasArray (JsonReader reader) throws IOException {List <Data> datas = new ArrayList <Data> (); reader. beginArray (); while (reader. hasNext () {datas. add (readData (reader);} reader. endArray (); return datas ;}

 

Get message object

/*** Use JsonReader to parse the json character * @ param reader * @ return * @ throws IOException */public Message readMessage (JsonReader reader) throws IOException {int error_code = 0; string reason = null; List <Data> result = null; // starts parsing the object reader. beginObject (); while (reader. hasNext () {// obtain the key name String name = reader. nextName (); if (name. equals ("error_code") {error_code = reader. nextInt ();} else if (name. equals ("reason") {reason = reader. nextString ();} else if (name. equals ("result") {// result corresponds to a json array set-> data reader. beginObject (); while (reader. hasNext () {String tagName = reader. nextName (); if (tagName. equals ("data") {result = readDatasArray (reader);} else {reader. skipValue () ;}} reader. endObject ();} else {reader. skipValue () ;}// end parsing reader. endObject (); return new Message (error_code, reason, result );}

 

Okay. Let's test

Message msg = mParser.readMessage(new JsonReader(new StringReader(jsonResult)));        System.out.println(msg.getResult());        List<Data> list = msg.getResult();        for (Data data : list) {            System.out.println(data);        }

Result:

Data [content = remember that when I was a child, a teacher asked me to write a text. The requirement was very simple. If it was to make her cry, it would be okay. The next day, my buddy handed the essay to the teacher. After the teacher opened it, He sneezed and cried. A teacher asked, "Is this composition really touching ?" The teacher cried and said, "Which bastard sprinkled pepper on it !", Unixtime = 1441871137, updatetime = 15:45:37] Data [content = playing the League of legends with a small voice player in the first 10 minutes. Suddenly, we couldn't move the ADC, and there was a faint roar in our headphones: "You don't cook here to play games, what kind of food do you make your children hungry? This day is not enough ." Then the ADC is down ., Unixtime = 1441870406, updatetime = 15:33:26] Data [content = today, we had a fight with people. Today, we stood up on the street and waited for a friend to come and ask for money. As soon as I saw it was a liar, I sent it to him. When he left, he came up with the following sentence: "No, you have met the dumb man !" As soon as I heard the fire, "you are dumb !" At last, my hands are swollen ., Unixtime = 1441870406, updatetime = 15:33:26] Data [content = a reporter interviewed the Dean of the mental hospital, how to determine the patient has been cured, can be discharged from the hospital. The dean said: "It is very easy to fill the bathtub with water, put a spoon next to a spoon, and ask to leave the bathtub empty ." The reporter said: "Oh! ." The dean said, "No, normally, the plug-in the bathtub will be unplugged .", Unixtime = 1441870406, updatetime = 15:33:26] Data [content = last night, my friend called me to go to kge and asked me to drive. At the ktv door, I got off the bus and handed the key to the waiter, saying, help me stop the car, and I gave him 100 tip by the way. I saw him look at me, return 100, and take 100 from his wallet, said, eldest brother, stop this car yourself! Tractor, I really cannot drive, I ......, Unixtime = 1441870383, updatetime = 15:33:03] Data [content = A friend gave me a very expensive coffee. After cooking a cup, I took the opportunity to educate my younger brother: "Life is like this cup of coffee, you smell sweet, but I drink bitter." The younger brother said, "Hey, you just need to smell the smell and I will drink the coffee .", Unixtime = 1441869206, updatetime = 15:13:26] Data [content = wife: "Dear, please tidy up your room today !" Husband: "How to organize it ?" Wife: "I will discard all your smelly shoes, sows, and sows ." Husband: "Obey! My wife, are they also lost ?" Wife: "Ah, is it yours ?" Husband: "I have to kneel down every day. It must be mine ." Wife: "You only have the right to use, and the ownership belongs to me. If you still dare to use it, you will kneel down to it later !", Unixtime = 1441868754, updatetime = 15:05:54] Data [content = a young woman feeds her son, and the child is so hungry that she is so angry that she is very emotional: this child, better than our organization leaders! It's a good sign. When I grow up, I must be the best !, Unixtime = 1441868586, updatetime = 15:03:06] Data [content = a woman asked: "My husband, do you like this every day? I spent the rest of my work with me ?" Her husband said, "The next month is acceptable. You can't afford it !", Unixtime = 1441868049, updatetime = 14:54:09] Data [content = the University was poor. In order to make some money to play online games, several old Wang dormitory buddies came up with a solution: "The boss helps people write their homework, the second child helps people write compositions, the old Three help people write love letters, and the old Wang help people write reviews." Later, four of them became the famous four treasures of wenfang ., Unixtime = 1441868049, updatetime = 14:54:09]

 

Now that the data source has been successfully parsed, it will be displayed in listview.

 

Here is a bad thing. We wrote a Message class, but android also provides the android. OS. Message class.

It is easy to confuse and will be considered to be changed to another class name later.

 

Let's take a look at it first.

 

Not yet to be continued ....

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.