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);
 

.

猜你喜欢

转载自blog.csdn.net/weixin_42012335/article/details/83378640