Android native build JSON and parse JSON

Source: Internet
Author: User

JSON Data is a lightweight data interchange format that is typically applied to data transfer between client and server interactions in Android. There are many jar packages on the web that parse JSON data , but it's all about Android native parsing JSON data, it is important to master the way that native Android parses JSON data.

The following is a package that generates JSON data and parses JSON data in Org.json

(1) Generate JSON data method:

For example, to generate a JSON text like this

{

"Phone": ["12345678", "87654321"],// array

"Name": "Dream9",// string

"Age": +,// value

"Address": {"Country": "China", "province": "Guangdong"},// object

}

try {jsonobject obj = new Jsonobject ();//First create an object Jsonarray phone = new Jsonarray ();//Add data to the array where the sequence number is incremented from 0 phone.put ("123456 "Hone.put");p ("87654321"), Obj.put ("Phone", "phone"), Obj.put ("name", "Dream9"), Obj.put ("Age", 100); Jsonobject address = new Jsonobject (), Address.put ("Country", "China"), Address.put ("province", "Jiangsu"); Obj.put (" Address ", address); LOG.E ("Huang", obj.tostring ());

Results:



(2) parsing the JSON data method (as in the above example):

private void Anaylse (string data) {try {jsonobject obj = new Jsonobject (string) data); Jsonarray phone = Obj.getjsonarray ("Phone"), for (int t=0; t<phone.length (); ++t) {log.e ("Huang", phone.getstring (t)) ;      Parse the phone array}log.e ("Huang", obj.getstring ("name")); LOG.E ("Huang", Obj.getint ("age") + ""); Jsonobject o = obj.getjsonobject ("Address"); LOG.E ("Huang", o.getstring ("Country")); LOG.E ("Huang", o.getstring ("province")); catch (Jsonexception e) {//TODO auto-generated catch Blocke.printstacktrace ();}}

Results:


Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.

Android native build JSON and parse JSON

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.