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(',', '&');
    }

 


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM