如何解析JSON文件?

时间:2010-06-08 19:55:51

标签: java json

简单的情况 -

  1. 读取json文件
  2. 发现所有键值对
  3. 比较键值对
  4. 我从json.org尝试了gson,包,但似乎无法与之相提并论。

    有人可以用Java提供一个关于如何获取文件的清晰样本,阅读它,最后使用json objec我可以从中获取键/值对。

    考虑一下:

    private void runThroughJson(JsonObject jsonObject) {
        for (final Entry<String, JsonElement> entry : jsonObject.entrySet()) {
    
            final String key = entry.getKey();
            final JsonElement value = entry.getValue();
    
            System.out.println(key + " - " + value);
    
            if (value.isJsonObject()) {
                runThroughJson(value.getAsJsonObject());
            } else {                
                int ix = value.getAsString().indexOf('[');
                int ig = value.getAsString().lastIndexOf(']');
    
                System.out.println(ix);
                System.out.println(ig);
    
                String a = value.getAsString().substring(ix, ig);
                JsonElement jsonElement = parser.parse(a);
                runThroughJson(jsonElement.getAsJsonObject());
            }
        }
    }
    

    从逻辑上讲,似乎没问题,但我得到一个例外:

    Exception in thread "main" java.lang.IllegalStateException
        at com.google.gson.JsonArray.getAsString(JsonArray.java:133)
        at com.cme.esg.bk.TryGson.runThroughJson(TryGson.java:46)
        at com.cme.esg.bk.TryGson.runThroughJson(TryGson.java:44)
        at com.cme.esg.bk.TryGson.goForIt(TryGson.java:32)
        at com.cme.esg.bk.TryGson.main(TryGson.java:16)
    

    你可以告诉我,我错过了。

3 个答案:

答案 0 :(得分:11)

使用Gson(假设您在json文件的顶层有对象{...}):

final JsonParser parser = new JsonParser();
final JsonElement jsonElement = parser.parse(new FileReader("/path/to/myfile"));
final JsonObject jsonObject = jsonElement.getAsJsonObject();

for (final Entry<String, JsonElement> entry : jsonObject.entrySet()) {
   final String key = entry.getKey();
   final JsonElement value = entry.getValue();
   ....
}

回应您的评论:

您当然应该避免从字符串重新解析json。使用类似的东西:

... else if (value.isJsonArray()) {
   final JsonArray jsonArray = value.getAsJsonArray();
   if (jsonArray.size() == 1) {
      runThroughJson(jsonArray.get(0));
   } else {
        // perform some error handling, since
        // you expect it to have just one child!
   }

} 

答案 1 :(得分:1)

我们使用Jaskson解析器,下面是示例代码:

protected T getJsonObject(InputStream inputStream, Class<T> className) throws JsonParseException,
      JsonMappingException, IOException {
    // Deserialize input to Json object
    ObjectMapper mapper = new ObjectMapper();

    T jsonSource = mapper.readValue(inputStream, className);
    return jsonSource;
}

以下是如何调用它的代码:

JsonEmployee jsonEmployee = getJsonObject(inputStream, JsonEmployee.class);

JsonEmployee.java只是POJO

答案 2 :(得分:0)

XStream适用于JSON: http://x-stream.github.io/json-tutorial.html

由于XStream的灵活架构,JSON映射的处理与处理XML文档一样简单。您所要做的就是使用适当的驱动程序初始化XStream对象,并准备将对象序列化为(和)JSON。

相关问题