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