Android skills-create JSON text and JSON parsing

Source: Internet
Author: User
Tags tojson
<span id="Label3"></p><p><p>Abstract: JSON data is very common in the Android development process, when requesting Server-side data, the Server-side returns is nothing more than three types: Html,xml,json. So learning JSON is very important for Android Programmers.</p></p><span style="color:#B22222"><span style="color:#B22222">What is JSON</span></span><p><p>Json:javascript Object Notation. As the name implies, JSON data originates from javascript, and people who have learned JavaScript (hereinafter referred to as js) know that when we create objects in the JS script, they are written in the form of Key-value Pairs. For example, We define this when we create a JSON object in Js:</p></p><p><p></p></p><pre name="code" class="javascript"><pre name="code" class="javascript">var person = {firstName: "John", lastName: "Doe", age:50, eyecolor: "blue"};</pre></pre><br><br><p><p></p></p><p><p><br></p></p><p><p>It is easy to see that the attributes are separated by commas, and the keys and values are separated by double quotation marks, and so are the JSON Data.</p></p><p><p><br></p></p><span style="color:#B22222"><span style="color:#B22222">data types for JSON</span></span><p><p>There are two types of data structures in Json.</p></p><strong><strong>Jsonobject</strong></strong><p><p>One is an unordered Jsonobject object that exists in the form of (key/value). objects are enclosed in curly braces, and the attributes are separated by Commas.</p></p><p><p></p></p><p><p>For example: {"name": "jack"}, This is the simplest JSON object, for this data format, the key value must be a string type, and for value, it can be a string, number, object, array and other data types.</p></p><p><p><br></p></p><strong><strong>Jsonarray</strong></strong><p><p>Another data format is the set of ordered value, which is known as Jsonarray. An array is an ordered collection of values, separated by commas between values and values, enclosed in Brackets.</p></p><p><p></p></p><p><p><br></p></p><span style="color:#B22222"><span style="color:#B22222">Creating JSON text</span></span><p><p>For example, we want to create the following types of Jjson Data:</p></p><p><p></p></p><pre name="code" class="javascript"><pre name="code" class="javascript">{"person": {"name": "zhangsan", "phone": ["123", "456"], "address": "guangdong"}}</pre></pre><br><br><p><p></p></p><strong><strong>creating with Jsonoject and Jsonarray</strong></strong><strong><strong></strong></strong><pre name="code" class="java"><pre name="code" class="java"> /** * Using Jsonobject and Jsonarray to create JSON objects * /public void Makejson () { try { jsonobject object = new Jsonobject (); Jsonobject person = new Jsonobject (); Name person.put ("name", "zhangsan"); Telephone Jsonarray phone = new Jsonarray (); Phone.put ("123"). put ("456"); Person.put ("phone", phone); Address person.put ("adress", "guangdong"); Object.put ("person", person); LOG.I ("json_log", object.tostring ()); } Catch (jsonexception e) { e.printstacktrace (); } }</pre></pre><br><br><p><p>Output results</p></p><p><p></p></p><strong><strong>Create with Jsonstringer</strong></strong><strong><strong></strong></strong><pre name="code" class="java"><pre name="code" class="java"> /** * Create JSON object via Jsonstringer * /public void Makejsonstringer () { try { jsonstringer jsontext = new Jsonstringer (); The first is {, the object begins. Object and EndObject must be paired with Jsontext.object (); Jsontext.key ("person"); Jsontext.object (); Jsontext.key ("name"); Jsontext.value ("zhangsan"); Jsontext.key ("phone"); The value of the key phone is an array. Array and Endarray must be paired with Jsontext.array (); Jsontext.value ("123"). value ("456"); Jsontext.endarray (); Jsontext.key ("address"); Jsontext.value ("guangdong"); Jsontext.endobject (); Jsontext.endobject (); LOG.I ("json_log", jsontext.tostring ()); } Catch (jsonexception Ex) { throw new runtimeexception (ex); } }</pre></pre><br><br><p><p>Output result:</p></p><p><p></p></p><span style="color:#B22222"><span style="color:#B22222">JSON parsing</span></span><strong><strong>1. Parse {"key", "Object"} type</strong></strong><strong><strong></strong></strong><pre name="code" class="javascript"><pre name="code" class="javascript">{"person": {"name": "zhangsan", "phone": ["123", "456"], "address": "guangdong"}}</pre></pre><br><br><p><p>Parsing code</p></p><p><p></p></p><pre name="code" class="java"><pre name="code" class="java">/** * JSON parsing * @param JSON * @return */public static String jsontost Ring (String json) {person person = new Person (); Try {//gets the entire JSON data jsonobject object = new Jsonobject (json); Resolves the outermost layer, obtaining the object value corresponding to the person key jsonobject Personobject = Object.getjsonobject ("person"); Parse each attribute inside the object value Person.setname (personobject.getstring ("name")); Property value is an array, use Jsonarray to get jsonarray Phonearray = Personobject.getjsonarray ("phone"); list<string> phone = new arraylist<> (); for (int i = 0; i < phonearray.length (); i++) {phone.add (String) phonearray.get (i)); } Person.setphone (phone); Person.setaddress (personobject.getstring ("address")); } catch (jsonexception E) {e.printstacktrace (); } return person.tostring (); }</pre></pre><br><br><p><p></p></p><p><p><br><br></p></p><p><p>Results</p></p><p><p></p></p><p><p><br></p></p><strong><strong>2. parsing {"Object"} type</strong></strong><strong><strong></strong></strong><pre name="code" class="javascript"><pre name="code" class="javascript">{"name": "zhangsan", "phone": ["123", "456"], "address": "guangdong"}</pre></pre><br><br><br><p><p>So Parsing:</p></p><p><p></p></p><pre name="code" class="java"><pre name="code" class="java"> /** * Parse JSON data for individual objects * @param json * @return * /public static string jsonparse (string Json) { person person = new Person (); Try { jsonobject personobject = new Jsonobject (json); Parse each attribute inside the object value person.setname (personobject.getstring ("name")); Property value is an array, use Jsonarray to get jsonarray Phonearray = Personobject.getjsonarray ("phone"); list<string> phone = new arraylist<> (); for (int i = 0; i < phonearray.length (); i++) { phone.add (String) phonearray.get (i)); } Person.setphone (phone); Person.setaddress (personobject.getstring ("address")); } Catch (jsonexception e) { e.printstacktrace (); } return person.tostring (); }</pre></pre><br><br><p><p></p></p><strong><strong>3. parsing {"value"} type</strong></strong><strong><strong></strong></strong><pre name="code" class="javascript"><pre name="code" class="javascript">["123", "456", "789"];</pre></pre><br><br><p><p>Parsing method:</p></p><p><p></p></p><pre name="code" class="java"><pre name="code" class="java"> /** * Parse JSON data for array type * @param json * @return * /public static list<string> Jsonparsetoarray ( String Json) { list<string> List = new arraylist<> (); Try { jsonarray array = new Jsonarray (json); For (int i=0; i<array.length (); i++) { list.add (String) array.get (i) } } catch (jsonexception e) { C13/>e.printstacktrace (); } return list; }</pre></pre><br><br><p><p></p></p><p><p><strong>Analytic summary</strong><br>JSON parsing is nothing more than through Jsonobject and Jsonarray constantly parse the data, in the final analysis of each kind of data can be decomposed into the above three of the most basic analysis, so as long as you master good Jsonobject and jsonarray, Even complex data types can be interpreted with ease.</p></p><p><p><br></p></p><span style="color:#B22222"><span style="color:#B22222">Gson</span></span><p><p>Gson is an open source Java API developed by Google that can be used for JSON creation and JSON parsing. Here is a basic introduction to Gson. Learn more about http://sites.google.com/site/gson/</p></p><p><p>First need to download Gson jar package, Self-degree niang.<br><br>secondly, we use Gson to create JSON and parse JSON to have corresponding javabean, so Gson can help us to implement the transformation of Bean and JSON more easily.<br><br>In the following example we are using the JavaBean of the person class:</p></p><p><p></p></p><pre name="code" class="java"><pre name="code" class="java"> public class person { private String name; Private list<string> phone; Private String address; Public person () { } public person (string name, list<string> phone, string address) { this.name = name;< C8/>this.phone = phone; this.address = address; } Public String getName () { return name; } public void SetName (String name) { this.name = name; } Public list<string> getphone () { return phone; } public void Setphone (list<string> phone) { this.phone = phone; } Public String getaddress () { return address; } public void setaddress (String address) { this.address = address; } @Override public String toString () { return "person{" + "name= '" + name + ' \ ' + ", phone=" + phone +< c34/> ", address= '" + address + ' \ ' + '} ';} }</pre></pre><br><br><p><p></p></p><strong><strong>Bean converted to JSON</strong></strong><strong><strong></strong></strong><pre name="code" class="java"><pre name="code" class="java"> /** * Gson converted to JSON * * @return JSON * /public String Beantojson () { //assign to a person instance List <String> phone = new arraylist<> (); Phone.add ("123"); Phone.add ("456"); person person = new Person ("jack", phone, "Guangzhou"); Instantiate Gson Gson Gson = new Gson (); Call Gson.tojson to convert the bean to JSON String JSON = Gson.tojson (person); return json; }</pre></pre><br><br><strong><strong>convert JSON to Bean</strong></strong><pre name="code" class="java"><pre name="code" class="java"> /** * JSON converted to Bean * @param JSON * @return * * * public String jsontobean (string json) { person person = new Person (); Gson Gson = new Gson (); Call Gson.fromjson to convert JSON to bean person = Gson.fromjson (json, person.class); return person.tostring (); }</pre></pre><br><br><p><p>Android skills-create JSON text and JSON parsing</p></p></span>

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.