Android uses Jsonreader to parse JSON

Source: Internet
Author: User

For this JSON:

{  "id": "3232",  "data": [{    "data1": "555",    "data2": "3243"    },    {     "data1": "888",     " Data2 ":" 777 "    }]  }

We can parse this out:

Import Java.io.ioexception;import java.io.inputstream;import Java.io.reader;import Java.io.stringreader;import Com.google.gson.stream.jsonreader;import Android.app.activity;import Android.content.context;import Android.os.bundle;public class TestActivity1 extends Activity {@Overrideprotected void OnCreate (Bundle Savedinstancestate) {super.oncreate (savedinstancestate);p arseassertdata ();} 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 ());p arseresponse (response);} catch (IOException ex) {ex.printstacktrace ();}} private void Parseresponse (reader response) throws IOException {Jsonreader reader = new Jsonreader (response); Reader.beginobject (); while (Reader.hasnext ()) {string name = Reader.nextname (); if ("id". Equals (name)) {String id = Reader.nextstring (); System.out.priNtln ("===id=" +id);        else if (name.equals ("data")) {Reader.beginarray (); while (Reader.hasnext ()) {reader.beginobject ();        String name1;            while (Reader.hasnext ()) {name1 = Reader.nextname ();            if (Name1.equals ("Data1")) {String S1 = reader.nextstring ();            System.out.println ("===s1=" +s1);            } else if (Name1.equals ("Data2")) {String s2 = reader.nextstring ();            System.out.println ("===s2=" +s2);            } else {reader.skipvalue (); }} reader.endobject ();} Reader.endarray ();} else {reader.skipvalue ();}} Reader.endobject (); Reader.close ();}}


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.