"Android" parsing json data in detail

Source: Internet
Author: User

Android parsing JSON data in detail
  1. JSON (JavaScript Object Notation) defines:

    A lightweight data interchange format with good readability and easy-to-write features. The industry's mainstream technology provides a complete solution (somewhat like regular expressions, which is supported in most languages today), enabling data exchange between different platforms. JSON uses a high-compatibility text format, and also has a similar behavior to the C language system. –json.org

  2. Structure of JSON:

    (1) Name/value Pairs (unordered): similar to the familiar keyed list, Hash table, disctionary, and associative array. There is another class "Bundle" in the Android platform that has similar behavior in some way.

    (2) Array (ordered): A set of ordered data lists.

    Object
    对象是一个无序的Name/Value Pairs集合。{ name:value , name:value , name:value ....  }例子:{ "name":"小猪","age":20 }
    Array
    Array是值(value)的有序集合。[ value , value , value ...... ] 值(value)可以是双引号括起来的字符串(string)、数值(number)、true、false、 null、对象(object)或者数组(array)。这些结构可以嵌套。字符串(string)是由双引号包围的任意数量Unicode字符的集合,使用反斜线转义。一个字符(character)即一个单独的字符串(character string)。 例如:\ + " \ / b f n r t u 进行转义。

    Example 1:array contains objects (object)

    [ {"id":1,"name":"小猪" ,"age”:22} , {"id":2,"name":"小猫","age”:23} ,  .......]

    Example 2: The same object can contain an array

    (1)一个对象包含1个数组,2个子对象    {"root":[{"id":"001","name":"小猪"},{"id":"002","name":"小猫"},{"id":"003","name":"小狗"}],     "total":3,     "success":true    }(2)也可以对象嵌套子对象,子对象再嵌套数组    {"calendar":         {"calendarlist":                 [                 {"id":"001","name":"小猪"},                 {"id":"002","name":"小猫"}                 ]         }     }

    In short, the format is diverse, can be nested with each other

Contains four JSON-related classes and a exception in Android:

    • Jsonobject
    • Jsonarray
    • Jsonstringer
    • Jsontokener
    • Jsonexception

1.JSONObject:

这是系统中有关JSON定义的基本单元,其包含一对儿(Key/Value)数值。它对外部(External:应用toString()方法输出的数值)调用的响应体现为一个标准的字符串(例如:{“JSON”: “Hello, World”},最外被大括号包裹,其中的Key和Value被冒号”:”分隔)。其对于内部(Internal)行为的操作格式略微,例如:初始化一个JSONObject实例,引用内部的put()方法添加数值:new JSONObject().put(“JSON”, “Hello, World!”),在Key和Value之间是以逗号”,”分隔。Value的类型包括:Boolean、JSONArray、JSONObject、Number、String或者默认值JSONObject.NULL object。有两个不同的取值方法:get(): 在确定数值存在的条件下使用,否则当无法检索到相关Key时,将会抛出一个Exception信息。opt(): 这个方法相对比较灵活,当无法获取所指定数值时,将会返回一个默认数值,并不会抛出异常。

2.SONArray:

它代表一组有序的数值。将其转换为String输出(toString)所表现的形式是用方括号包裹,数值以逗号”,”分隔(例如:[value1,value2,value3],大家可以亲自利用简短的代码更加直观的了解其格式)。这个类的内部同样具有查询行为,get()和opt()两种方法都可以通过index索引返回指定的数值,put()方法用来添加或者替换数值。同样这个类的value类型可以包括:Boolean、JSONArray、JSONObject、Number、String或者默认值JSONObject.NULL object。

3.JSONStringer:

根据官方的解释,这个类可以帮助快速和便捷的创建JSONtext。其最大的优点在于可以减少由于格式的错误导致程序异常,引用这个类可以自动严格按照JSON语法规则(syntaxrules)创建JSON text。每个JSONStringer实体只能对应创建一个JSON text。根据下边的实例来了解其它相关信息:Java示例代码:    String myString = new JSONStringer().object()        .key("name")       .value("小猪")        .endObject()       .toString();  结果是一组标准格式的JSON text:{"name" : "小猪"}其中的.object()和.endObject()必须同时使用,是为了按照Object标准给数值添加边界。同样,针对数组也有一组标准的方法来生成边界.array()和.endArray()。

4.JSONTokener:

这个是系统为JSONObject和JSONArray构造器解析JSON source string的类,它可以从source string中提取数值信息。

5.JSONException:

是JSON.org类抛出的异常信息。
The following is a full application example: Apply Jsonobject to store map type values:

Java Sample code:

public static JSONObject getJSON(Map map) {       Iterator iter = map.entrySet().iterator();       JSONObject holder = new JSONObject();       while (iter.hasNext()) {           Map.Entry pairs = (Map.Entry) iter.next();           String key = (String) pairs.getKey();           Map m = (Map) pairs.getValue();           JSONObject data = new JSONObject();           try {               Iterator iter2 = m.entrySet().iterator();               while (iter2.hasNext()) {                   Map.Entry pairs2 = (Map.Entry) iter2.next();                   data.put((String) pairs2.getKey(), (String) pairs2                           .getValue());               }               holder.put(key, data);           } catch (JSONException e) {               Log.e("Transforming", "There was an error packaging JSON", e);           }       }       return holder;   }  
The following is a detailed example:

Java Sample code:

Import Java.io.ByteArrayOutputStream;   Import Java.io.InputStream;   Import java.net.*;   Import java.util.ArrayList;   Import Java.util.HashMap;   Import java.util.List;   Import Java.util.Map;   Import Org.json.JSONArray;   Import Org.json.JSONObject;   Import Android.util.Log; public class JSON {/** * gets the "array form" JSON data, * data form: [{"id": 1, "name": "Piglet"},{"id": 2, "name": "Kitten"}] * @p Aram Path webpage * @return returns List * @throws Exception */public static list<map<string, Strin           G>> Getjsonarray (String path) throws Exception {string json = NULL;           list<map<string, string>> list = new arraylist<map<string, string>> ();           map<string, string> map = null;           URL url = new URL (path);           HttpURLConnection conn = (httpurlconnection) url.openconnection ();//using the HttpURLConnection object, we can get the Web page data from the network.   Conn.setconnecttimeout (5 * 1000); The unit is in milliseconds and the timeout is set to 5 seconds conn.seTrequestmethod ("GET"); HttpURLConnection is requested via the HTTP protocol, so you need to set the request mode, you can not set, because the default is get if (conn.getresponsecode () = = 200) {//Determine if the request code is 200 yards, otherwise failed inputstream is = Conn.getinputstream ();   Get input stream byte[] data = Readstream (IS);        Convert input flow to character array json = new String (data); Converts a character array to a string//data form: [{"id": 1, "name": "Piglet", "Age": 22},{"id": 2, "name": "Kitten", "Age": +}] Jsonarray Jsonarray = new Jsonarray (JSON);  The data is directly in an array form, so you can read the JSON data directly with the frame Jsonarray provided by Android and convert it to an array for (int i = 0; i < jsonarray.length (); i++) {Jsonobject item = jsonarray.getjsonobject (i);//Each record is also made up of several object objects int id = item.ge     TINT ("id");                   Gets the value of the object that corresponds to String name = item.getstring ("name"); Map = new hashmap<string, string> ();                   Store in Map map.put ("id", ID + "");                   Map.put ("name", name); List.add (Map);               }}//*********** test Data ****************** for (map<string, string> list2:list) {               String id = list2.get ("id");               String name = List2.get ("name"); LOG.I ("abc", "ID:" + id + "|           Name: "+ name");       } return list; }/** * Gets the "object form" JSON data, * data form: {"Total": 2, "Success": true, "Arraydata": [{"id": 1, "name": "Piglet"},{"id": 2, "Nam E ":" Kitten "}]} * @param path webpage * @return return List * @throws Exception */public static LIST&LT ; Map<string, string>> getjsonobject (String path) throws Exception {list<map<string, String>&gt ;           List = new arraylist<map<string, string>> ();           map<string, string> map = null;           URL url = new URL (path);           HttpURLConnection conn = (httpurlconnection) url.openconnection ();//using the HttpURLConnection object, we can get the Web page data from the network.   Conn.setconnecttimeout (5 * 1000); // The unit is in milliseconds and the timeout is set to 5 seconds Conn.setrequestmethod ("GET"); HttpURLConnection is requested via the HTTP protocol, so you need to set the request mode, you can not set, because the default is get if (conn.getresponsecode () = = 200) {//Determine if the request code is 200 yards, otherwise failed inputstream is = Conn.getinputstream ();   Get input stream byte[] data = Readstream (IS); Convert input flow to character array string json = new string (data);               Converts a character array to a string//data form: {"Total": 2, "Success": true, "Arraydata": [{"id": 1, "name": "Piglet"},{"id": 2, "name": "Kitten"}]}     Jsonobject jsonobject=new Jsonobject (JSON);               The returned data form is an object type, so it can be converted directly to an object int total=jsonobject.getint ("total");               Boolean Success=jsonobject.getboolean ("Success"); LOG.I ("abc", "Total:" + All + "|   Success: "+ success);               Test data Jsonarray Jsonarray = Jsonobject.getjsonarray ("Arraydata");//There is an array of data, you can use Getjsonarray to get the array for (int i = 0; i < jsonarray.length (); i++) {Jsonobject item = Jsonarray.getJsonobject (i);     Get each object int id = item.getint ("id");                   Gets the value of the object that corresponds to String name = item.getstring ("name"); Map = new hashmap<string, string> ();                   Store in Map map.put ("id", ID + "");                   Map.put ("name", name);               List.add (map);               }}//*********** test Data ****************** for (map<string, string> list2:list) {               String id = list2.get ("id");               String name = List2.get ("name"); LOG.I ("abc", "ID:" + id + "|           Name: "+ name");       } return list; }/** * Gets a complex type of JSON data * data form: {"name": "Piglet", "Age": "Content": {"Questionst Otal ": 2," questions ": [{" Question ":" What's your name? "," Answer ":" Piggy "},{" question ":" What ' s your Age "," Answer ":" ""} "}}} * @param path web paths * @return returnList * @throws Exception */public static list<map<string, string>> Getjson (String path) thro           WS Exception {list<map<string, string>> List = new arraylist<map<string, string>> ();           map<string, string> map = null;           URL url = new URL (path);           HttpURLConnection conn = (httpurlconnection) url.openconnection ();//using the HttpURLConnection object, we can get the Web page data from the network.   Conn.setconnecttimeout (5 * 1000);       The unit is in milliseconds and the timeout is set to 5 seconds Conn.setrequestmethod ("GET"); HttpURLConnection is requested via the HTTP protocol, so you need to set the request mode, you can not set, because the default is get if (conn.getresponsecode () = = 200) {//Determine if the request code is 200 yards, otherwise failed inputstream is = Conn.getinputstream ();   Get input stream byte[] data = Readstream (IS); Convert input flow to character array string json = new string (data); Converts an array of characters to a string/* data form: {"name": "Piglet", "age": all, "content ": {" Questionstotal ": 2,                             "Questions": [{"Question": "What's your name?", "Answer": "Piglet"},{"question": "What ' s your A GE "," answer ":" ~ "}]}} */Jsonobject Jsonobje     Ct=new Jsonobject (JSON);                      The returned data form is an object type, so it can be converted directly to an object String name=jsonobject.getstring ("name");               int Age=jsonobject.getint ("age"); LOG.I ("abc", "Name:" + name + "| Age: "+ age");       Test data Jsonobject Contentobject=jsonobject.getjsonobject ("content");    Gets the object in the object String questionstotal=contentobject.getstring ("Questionstotal");   Gets a value in the object LOG.I ("abc", "Questionstotal:" + questionstotal);     Test data Jsonarray Contentarray=contentobject.getjsonarray ("questions"); Gets the array in the object for (int i = 0; i < contentarray.length (); i++) {Jsonobject item = ContentA Rray.getjsonobject (i);            Get each object       String question = item.getstring ("question");                   Gets the value of the object that corresponds to String answer = item.getstring ("answer"); Map = new hashmap<string, string> ();                   Store in map inside Map.put ("question", question);                   Map.put ("answer", answer);               List.add (map);               }}//*********** test Data ****************** for (map<string, string> list2:list) {               String question = List2.get ("question");               String answer = list2.get ("answer"); LOG.I ("abc", "Question:" + question + "|           Answer: "+ answer);       } return list;      }/** * Convert input stream into character array * @param inputstream input Flow * @return Character array * @throws Exception */ public static byte[] Readstream (InputStream inputstream) throws Exception {Bytearrayoutputstream bout = NE           W Bytearrayoutputstream ();      byte[] buffer = new byte[1024];     int len = 0;           while (len = inputstream.read (buffer))! =-1) {bout.write (buffer, 0, Len);           } bout.close ();           Inputstream.close ();       return Bout.tobytearray ();   }   }

Welcome Androider Attention Public Number: Love Android

"Android" parsing json data in detail

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.