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

 

posted @ 2018-01-08 09:15  NoYone  阅读(1653)  评论(0编辑  收藏  举报