我们通常在已知格式的情况下直接使用 JSONObject,JSONArray, 但是如果遇到需要判断格式呢?
- try{Object object = JSON.parse(a);
- if (object instanceof JSONObject){
- //JSONObject
- }
- if (object instanceof JSONArray){
- //JSONArray
- }
- }catch (com.alibaba.fastjson.JSONException e){
- // 非 JSON 字符串
- }
- 2.org.json.JSON
直接使用 JSON 库做解析的情况不多, 但是这里也稍微写一下
- log.info(JSON.parse(jsonStr).getClass().getName());
- try {
- Object json = new JSONTokener(jsonStr).nextValue();
- log.info( json.getClass().toString());
- // json.toString();
- if(json instanceof JSONObject){
- log.info("is JSONObject");
- JSONObject jsonObject = (JSONObject)json;
- //further actions on jsonObjects
- //...
- }else if (json instanceof JSONArray){
- log.info("is JSONArray");
- JSONArray jsonArray = (JSONArray)json;
- //further actions on jsonArray
- //...
- }
- }catch (Exception e){
- e.printStackTrace();
- }
3.GSON, 也是蛮强大的一个库, 没有依赖包, 只是在反射到 Map 的使用上有点麻烦.
GSON 里面最有意思的就是 JsonPrimitive, 原始 JSON.
先给代码
- String str = "";
- JsonParser jsonParser = new JsonParser();
- try{
- JsonElement jsonElement = jsonParser.parse(str);
- log.info("jsonElement"+jsonElement.getClass().getName());
- if (jsonElement.isJsonObject()){
- //JsonObject
- log.info(jsonElement.getAsJsonObject().get("aa").getAsString());
- }
- if (jsonElement.isJsonArray()){
- //JsonArray
- log.info(jsonElement.getAsJsonArray().get(0).getAsJsonObject().get("aa").getAsString());
- }
- if (jsonElement.isJsonNull()){
- // 空字符串
- log.info(jsonElement.getAsString());
- }
- if (jsonElement.isJsonPrimitive()){
- log.info(jsonElement.getAsString());
- }
- }catch (Exception e){
- // 非法
- // e.printStackTrace();
- log.info("非法"+e.getMessage());
- }
可知, GSON 中定义了四个 JSON 类型, 分别是 JSONObject,JSONArray,JSONPrimitive,JSONNull.
但是官方对 JSON 的严格定义是 {} 为 JSONObject,[]为 JSONArray.
所以只用 JsonElement jsonElement = jsonParser.parse(str); 能正常解析的字符串并不意味着是一个合法的 JSON, 必须满足
jsonElement.isJsonObject()或者 jsonElement.isJsonArray().
另说一个题外话, 关于对 jsonElement.getAsJsonPrimitive()方法的理解.
JsonPrimitive 即时指 JSON value 的原始数据, 包含三种类型, 数字, 双引号包裹的字符串, 布尔.
所以 JsonPrimitive.toString 得到的不是实际的值, 而是 JSON 中的: 后面的完整内容, 需要再做一次 getAs.
例如
- String str = "{\"aa\":\"aa\"}";
- JsonElement jsonElement = jsonParser.parse(str);
- log.info(jsonElement.getAsJsonObject().get("aa").getAsString());
- str = "{\"aa\":true}";
- jsonElement = jsonParser.parse(str);
- jsonElement.getAsJsonObject().get("aa").getAsBoolean();
- str = "{\"aa\":1.2}";
- jsonElement.getAsJsonObject().get("aa").getAsBigDecimal();
所以 Gson 还有一个好处就是自带转换为 java 常规类型.
来源: http://www.bubuko.com/infodetail-2619205.html