1. 程式人生 > >org.json.JSONObject 與 com.alibaba.fastjson.JSONObject 中時間轉換不同

org.json.JSONObject 與 com.alibaba.fastjson.JSONObject 中時間轉換不同

    業務需求呼叫了阿里的內容安全的相關介面。程式碼示例如下:

        Map<String, Object> task = new LinkedHashMap<String, Object>();
        task.put("dataId", UUID.randomUUID().toString());
        task.put("url", "http://f.hiphotos.baidu.com/image/pic/item/aa18972bd40735fa13899ac392510fb30f24084b.jpg");
        task.put("time", new Date());

        tasks.add(task);
        com.alibaba.fastjson.JSONObject data = new JSONObject();
        data.put("scenes", Arrays.asList("porn","terrorism"));
        data.put("tasks", tasks);
         imageSyncScanRequest.setHttpContent(data.toJSONString().getBytes("UTF-8"), "UTF-8", FormatType.JSON);

        

                在專案中編寫的時候我把com.alibaba.fastjson.JSONObject 換成了     org.json.JSONObject  後 。發現呼叫阿里介面一直報json parse error 錯誤。報錯程式碼如下:

 List<Map<String, Object>> tasks = new ArrayList<Map<String, Object>>();
        Map<String, Object> task = new LinkedHashMap<String, Object>();
        task.put("dataId", UUID.randomUUID().toString());
        task.put("url", "http://f.hiphotos.baidu.com/image/pic/item/aa18972bd40735fa13899ac392510fb30f24084b.jpg");
        task.put("time", new Date());

        tasks.add(task);
        org.json.JSONObject data1 = new org.json.JSONObject();
        data1.put("scenes", Arrays.asList("porn","terrorism"));
        data1.put("tasks", tasks);
        imageSyncScanRequest.setHttpContent(data1.toString().getBytes("UTF-8"), "UTF-8", FormatType.JSON);

列印兩個json後發現問題。com.alibaba.fastjson.JSONObject 的toJSONString 中的時間是時間戳,而org.json.JSONObject 的 toString()中時間是有格式的.所以一直會報json解析錯誤:兩種方法輸出列印結果如下

// com.alibaba.fastjson.JSONObject 的toJSONString()方法列印結果

{"scenes":["porn","terrorism"],"tasks":[{"dataId":"6c0b4053-af2e-484e-9136-88c67060baa7","url":"http://f.hiphotos.baidu.com/image/pic/item/aa18972bd40735fa13899ac392510fb30f24084b.jpg","time":1540447702160}]}


// org.json.JSONObject 的toString() 放發的列印結果

{"scenes":["porn","terrorism"],"tasks":[{"dataId":"6c0b4053-af2e-484e-9136-88c67060baa7","time":"Thu Oct 25 14:08:22 CST 2018","url":"http://f.hiphotos.baidu.com/image/pic/item/aa18972bd40735fa13899ac392510fb30f24084b.jpg"}]}
更改程式碼,如果用org.json.JSONObject 的話 向裡邊存時間的時候掉一下時間的getTime()方法就好了。

更改後:

 List<Map<String, Object>> tasks = new ArrayList<Map<String, Object>>();
        Map<String, Object> task = new LinkedHashMap<String, Object>();
        task.put("dataId", UUID.randomUUID().toString());
        task.put("url", "http://f.hiphotos.baidu.com/image/pic/item/aa18972bd40735fa13899ac392510fb30f24084b.jpg");
        task.put("time", new Date().getTime();

        tasks.add(task);
        org.json.JSONObject data1 = new org.json.JSONObject();
        data1.put("scenes", Arrays.asList("porn","terrorism"));
        data1.put("tasks", tasks);
        imageSyncScanRequest.setHttpContent(data1.toString().getBytes("UTF-8"), "UTF-8", FormatType.JSON);
 

.