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