【问题标题】:check if file is json, java检查文件是否为 json、java
【发布时间】:2010-09-09 18:31:54
【问题描述】:

使用 Java 有没有一种简单的方法来检查给定文件是否符合 json 格式?

使用 gson,我能做的最好的事情是:

private final JsonParser parser = new JsonParser();
jsonElement = parser.parse(new FileReader(fileName));

    if (jsonElement.isJsonObject()) {
        return true;
    } else {
        return false;
    }

有更简洁的想法吗?

【问题讨论】:

    标签: java json gson


    【解决方案1】:

    如果 JSON 不可解析,Gson 将抛出 JsonParseException。您只需在try 中使用JsonParser#parse() catch

    try {
        new JsonParser().parse(jsonSource);
        // Valid.
    } catch (JsonParseException e) {
        // Invalid.
    }
    

    【讨论】:

      猜你喜欢
      • 2010-11-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-09-28
      • 2015-08-11
      • 2020-12-27
      • 2013-03-31
      相关资源
      最近更新 更多