• Java JSON数据处理


    比方说要处理这么一段数据。

    {"data":[{"salt":"","plaintext":"xiaoxu","time":"1507462954","hash":"0b4fd093bd6a97154001542e682a9289"}]}

    在{}里面叫做JSONObject,而中括号里面的是JSONArray。

    一段JSON数据,当然了,把它当做一个字符串各种split当然可以了。但是有处理JSON的工具嘛反正,还是用一下。

    1. 用GSON这个工具(JSON.jar)。

    import com.google.gson.*;
        hashRes="{"data":[{"salt":"","plaintext":"xiaoxu","time":"1507462954","hash":"0b4fd093bd6a97154001542e682a9289"}]}";   
        Gson gson = new Gson();
        HashMap<String, Object> hashMap = new HashMap<String, Object>();
        hashMap = gson.fromJson(hashesRes, hashMap.getClass());
        Object object = hashMap.get("data");
        String jsonArray = object.toString();
        String[] strings = jsonArray.split("\,");
    
        System.out.println(strings[0].substring(2) + strings[1]);

     2. 用fastjson将JSON转为map。

    import com.alibaba.fastjson.JSONArray;
    import com.alibaba.fastjson.JSONObject;
        //将json转为map
        hashRes="{"data":[{"salt":"","plaintext":"xiaoxu","time":"1507462954","hash":"0b4fd093bd6a97154001542e682a9289"}]}";
        Map<String, Object> map = null;
        map = (Map<String, Object>) JSONObject.parse(hashesRes);

     另外加一种常见情形:将JSON数据转换为一个字典方便post传输。(直接用的正则)

        public static String JSON2POST(JSONObject JSONStatus){
            String data2POST = JSONStatus.toJSONString().replaceAll("[{}"]", "");
            data2POST = data2POST.replace(':', '=');
            return data2POST = data2POST.replace(',', '&');
        }
  • 相关阅读:
    简易仿ios菊花加载loading图
    android 仿微信表情雨下落!
    android view 转Bitmap 生成截图
    设计模式——享元模式
    虚拟内存技术原理解析
    读史——回望勾吴
    android日志搜集原理及方案比较
    java四种引用及在LeakCanery中应用
    读史——秦历史概况
    git使用总结
  • 原文地址:https://www.cnblogs.com/NoYone/p/8241070.html
Copyright © 2020-2023  润新知