zoukankan      html  css  js  c++  java
  • 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(',', '&');
        }
  • 相关阅读:
    自定义控件类
    初探ListView和Adapter
    探究android控件及布局
    页面布局之一边固定一边自适应
    cavans 文字换行
    移动开发01 页面取消横向滚动条
    移动端rem,scale动态设置
    map,area标签
    css3属性——border-radius用法
    z-index要同级比较,absolute包含块外有overflow-hidden
  • 原文地址:https://www.cnblogs.com/NoYone/p/8241070.html
Copyright © 2011-2022 走看看