Android uses Gson to parse JSON

Source: Internet
Author: User

Gson is an object parsing json, very useful, introduce a site http://json.parser.online.fr/can help us see a string is not JSON

For JSON files

{"  id": "3232",  "data": {    "data1": {      "name": "Xiaoming",      "age": "  " "}}}

If you use Gson to parse, define the corresponding class with this JSON node, we use MyData to represent the parsed JSON object, data to represent the object that resolves the data node, DATA1 class to represent the object of the Data1 node

public class MyData {int <strong>id</strong>;D ata <strong>data</strong>;} public class Data {Data1 <strong>data1</strong>;} public class Data1 {String <strong>name</strong>; String <strong>age</strong>;}

Note that the name of the member variable must be the same as the name of the node (bold characters)

We put the JSON file under the assets, and when we parse it, we write:

public void Parseassertdata () {InputStream was = null;try {is = This.getassets (). Open ("Ss.json", context.mode_private); int length = is.available (); byte[] buffer = new Byte[length];is.read (buffer); String temp = new string (buffer); Reader response = new StringReader (temp.tostring ()); Gson Gson = new Gson (); MyData MyData = Gson.fromjson (Response,mydata.class); System.out.println ("===age=" +mydata.data.data1.age); catch (IOException ex) {ex.printstacktrace ();}}

The ability to download this very easy sample (including Gson's jar package) in http://download.csdn.net/detail/baidu_nod/7643643

Android uses Gson to parse JSON

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.