gson判断字符串是否是json
Java有个字符串,如何判断它是json字符串?
现在主流的方法是啥呢?
gson原来有个JsonParser,现在弃用了,
String tmp = "{\"hello\":\"world\"}";System.out.println(new JsonParser().parse(tmp));;
难道只能
try {    Gson gson = new Gson();
    gson.fromJson(tmp, Map.class);
} catch (Exception e) {
    // todo
}
回答:
专门去看了一下Gson,你的说法gson原来有个JsonParser,现在弃用了,其实是错误的。
当前最新版本为: 2.9.0  https://mvnrepository.com/artifact/com.google.code.gson/gson

他的意思是:没必要实例化该类,直接使用静态方法即可。所以,可以继续使用:
/** * Parses the specified JSON string into a parse tree
 *
 * @param json JSON text
 * @return a parse tree of {@link JsonElement}s corresponding to the specified JSON
 * @throws JsonParseException if the specified text is not valid JSON
 */
public static JsonElement parseString(String json) throws JsonSyntaxException {
  return parseReader(new StringReader(json));
}
一个点赞比较高的答案:https://stackoverflow.com/questions/10174898/how-to-check-whether-a-given-string-is-valid-json-in-java
import org.json.*;public boolean isJSONValid(String test) {
    try {
        new JSONObject(test);
    } catch (JSONException ex) {
        // edited, to include @Arthur's comment
        // e.g. in case JSONArray is valid as well...
        try {
            new JSONArray(test);
        } catch (JSONException ex1) {
            return false;
        }
    }
    return true;
}
已参与了 SegmentFault 思否社区 10 周年「问答」打卡 ,欢迎正在阅读的你也加入。
以上是 gson判断字符串是否是json 的全部内容, 来源链接: utcz.com/p/944494.html

