1.Fastjson
我们通常在已知格式的情况下直接使用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常规类型。
Fastjson, Gson, org.json.JSON三者对于JSONObject及JSONArray的判断
原文地址:https://www.cnblogs.com/huanghongbo/p/9094979.html