• JSON的三种解析方式


    http://www.2cto.com/kf/201401/270452.html

    一、什么是JSON?

    JSON是一种取代XML的数据结构,和xml相比,它更小巧但描述能力却不差,由于它的小巧所以网络传输数据将减少更多流量从而加快速度。

    JSON就是一串字符串 只不过元素会使用特定的符号标注。

    {} 双括号表示对象

    [] 中括号表示数组

    "" 双引号内是属性或值

    : 冒号表示后者是前者的值(这个值可以是字符串、数字、也可以是另一个数组或对象)

    所以 {"name": "Michael"} 可以理解为是一个包含name为Michael的对象

    而[{"name": "Michael"},{"name": "Jerry"}]就表示包含两个对象的数组

    当然了,你也可以使用{"name":["Michael","Jerry"]}来简化上面一部,这是一个拥有一个name数组的对象

    二、JSON解析之传统的JSON解析

    1、生成JSOn字符串

    1
    2
    3
    4
    5
    public static String createJsonString(String key, Object value) {
            JSONObject jsonObject = new JSONObject();
            jsonObject.put(key, value);
            return jsonObject.toString();
        }

    2、解析JSON字符串

    分为以下三种情况,一个JavaBean,一个List数组,一个嵌套Map的List数组:

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
    65
    66
    67
    68
    69
    70
    71
    72
    73
    74
    75
    76
    77
    78
    79
    80
    81
    82
    83
    84
    85
    86
    87
    88
    89
    90
    91
    92
    93
    import java.util.ArrayList;
    import java.util.HashMap;
    import java.util.Iterator;
    import java.util.List;
    import java.util.Map;
     
    import org.json.JSONArray;
    import org.json.JSONObject;
     
    import com.android.myjson.domain.Person;
     
    /**
     * 完成对json数据的解析
     *
     */
    public class JsonTools {
     
     
        public static Person getPerson(String key, String jsonString) {
            Person person = new Person();
            try {
                JSONObject jsonObject = new JSONObject(jsonString);
                JSONObject personObject = jsonObject.getJSONObject("person");
                person.setId(personObject.getInt("id"));
                person.setName(personObject.getString("name"));
                person.setAddress(personObject.getString("address"));
            } catch (Exception e) {
                // TODO: handle exception
            }
            return person;
        }
     
        public static List<person> getPersons(String key, String jsonString) {
            List<person> list = new ArrayList<person>();
            try {
                JSONObject jsonObject = new JSONObject(jsonString);
                // 返回json的数组
                JSONArray jsonArray = jsonObject.getJSONArray(key);
                for (int i = 0; i < jsonArray.length(); i++) {
                    JSONObject jsonObject2 = jsonArray.getJSONObject(i);
                    Person person = new Person();
                    person.setId(jsonObject2.getInt("id"));
                    person.setName(jsonObject2.getString("name"));
                    person.setAddress(jsonObject2.getString("address"));
                    list.add(person);
                }
            } catch (Exception e) {
                // TODO: handle exception
            }
            return list;
        }
     
        public static List<string> getList(String key, String jsonString) {
            List<string> list = new ArrayList<string>();
            try {
                JSONObject jsonObject = new JSONObject(jsonString);
                JSONArray jsonArray = jsonObject.getJSONArray(key);
                for (int i = 0; i < jsonArray.length(); i++) {
                    String msg = jsonArray.getString(i);
                    list.add(msg);
                }
            } catch (Exception e) {
                // TODO: handle exception
            }
            return list;
        }
     
        public static List<map<string, object="">> listKeyMaps(String key,
                String jsonString) {
            List<map<string, object="">> list = new ArrayList<map<string, object="">>();
            try {
                JSONObject jsonObject = new JSONObject(jsonString);
                JSONArray jsonArray = jsonObject.getJSONArray(key);
                for (int i = 0; i < jsonArray.length(); i++) {
                    JSONObject jsonObject2 = jsonArray.getJSONObject(i);
                    Map<string, object=""> map = new HashMap<string, object="">();
                    Iterator<string> iterator = jsonObject2.keys();
                    while (iterator.hasNext()) {
                        String json_key = iterator.next();
                        Object json_value = jsonObject2.get(json_key);
                        if (json_value == null) {
                            json_value = "";
                        }
                        map.put(json_key, json_value);
                    }
                    list.add(map);
                }
            } catch (Exception e) {
                // TODO: handle exception
            }
            return list;
        }
    }</string></string,></string,></map<string,></map<string,></map<string,></string></string></string></person></person></person>

    三、JSON解析之GSON

    1、生成JSON字符串

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    import com.google.gson.Gson;
     
    public class JsonUtils {
     
        public static String createJsonObject(Object obj) {
            Gson gson = new Gson();
            String str = gson.toJson(obj);
            return str;
     
        }
    }

    二、解析JSON

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
    65
    66
    67
    68
    69
    70
    71
    72
    73
    74
    75
    76
    77
    78
    79
    80
    import java.util.ArrayList;
    import java.util.List;
    import java.util.Map;
     
    import com.google.gson.Gson;
    import com.google.gson.reflect.TypeToken;
     
    ;
    public class GsonTools {
     
        public GsonTools() {
            // TODO Auto-generated constructor stub
        }
     
        /**
         * @param <t>
         * @param jsonString
         * @param cls
         * @return
         */
        public static <t> T getPerson(String jsonString, Class<t> cls) {
            T t = null;
            try {
                Gson gson = new Gson();
                t = gson.fromJson(jsonString, cls);
            } catch (Exception e) {
                // TODO: handle exception
            }
            return t;
        }
     
        /**
         * 使用Gson进行解析 List<person>
         *
         * @param <t>
         * @param jsonString
         * @param cls
         * @return
         */
        public static <t> List<t> getPersons(String jsonString, Class<t> cls) {
            List<t> list = new ArrayList<t>();
            try {
                Gson gson = new Gson();
                list = gson.fromJson(jsonString, new TypeToken<list<t>>() {
                }.getType());
            } catch (Exception e) {
            }
            return list;
        }
     
        /**
         * @param jsonString
         * @return
         */
        public static List<string> getList(String jsonString) {
            List<string> list = new ArrayList<string>();
            try {
                Gson gson = new Gson();
                list = gson.fromJson(jsonString, new TypeToken<list<string>>() {
                }.getType());
            } catch (Exception e) {
                // TODO: handle exception
            }
            return list;
        }
     
        public static List<map<string, object="">> listKeyMaps(String jsonString) {
            List<map<string, object="">> list = new ArrayList<map<string, object="">>();
            try {
                Gson gson = new Gson();
                list = gson.fromJson(jsonString,
                        new TypeToken<list<map<string, object="">>>() {
                        }.getType());
            } catch (Exception e) {
                // TODO: handle exception
            }
            return list;
        }
    }
    </list<map<string,></map<string,></map<string,></map<string,></list<string></string></string></string></list<t></t></t></t></t></t></t></person></t></t></t>


    三、JSON解析之FastJSON

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    import java.util.ArrayList;
    import java.util.List;
    import java.util.Map;
     
    import com.alibaba.fastjson.JSON;
    import com.alibaba.fastjson.TypeReference;
     
    public class JsonTool {
     
        public static <t> T getPerson(String jsonstring, Class<t> cls) {
            T t = null;
            try {
                t = JSON.parseObject(jsonstring, cls);
            } catch (Exception e) {
                // TODO: handle exception
            }
            return t;
        }
     
        public static <t> List<t> getPersonList(String jsonstring, Class<t> cls) {
            List<t> list = new ArrayList<t>();
            try {
                list = JSON.parseArray(jsonstring, cls);
            } catch (Exception e) {
                // TODO: handle exception
            }
            return list;
        }
     
        public static <t> List<map<string, object="">> getPersonListMap1(
                String jsonstring) {
            List<map<string, object="">> list = new ArrayList<map<string, object="">>();
            try {
                list = JSON.parseObject(jsonstring,
                        new TypeReference<list<map<string, object="">>>() {
                        }.getType());
     
            } catch (Exception e) {
                // TODO: handle exception
            }
     
            return list;
        }
    }</list<map<string,></map<string,></map<string,></map<string,></t></t></t></t></t></t></t></t>

    总结:

    JSON对于移动设备来说,尤其对于网络环境较差和流量限制的情况下,相对于XML格式的数据传输会更节省流量,传输效率更高。在这三种解析方式中FastJson是效率最高的,推荐使用。

  • 相关阅读:
    trackr: An AngularJS app with a Java 8 backend – Part III
    trackr: An AngularJS app with a Java 8 backend – Part II
    21. Wireless tools (无线工具 5个)
    20. Web proxies (网页代理 4个)
    19. Rootkit detectors (隐形工具包检测器 5个)
    18. Fuzzers (模糊测试器 4个)
    16. Antimalware (反病毒 3个)
    17. Debuggers (调试器 5个)
    15. Password auditing (密码审核 12个)
    14. Encryption tools (加密工具 8个)
  • 原文地址:https://www.cnblogs.com/leaven/p/5135624.html
Copyright © 2020-2023  润新知