如何解析JSON文件? [英] How to parse JSON file?

查看:118
本文介绍了如何解析JSON文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

简单情况 -


  1. 读取json文件

  2. 发现所有键值对

  3. 比较键值对

我从json.org尝试过gson包,但是可以我似乎已经走得很远。

I tried gson, package from json.org, but can't seem to get far with it.

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

Can someone please provide a clear sample in Java on how to take a file, read it, end up with json objec I can get key/value pairs from.

考虑一下:

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());
        }
    }
}

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

Logically, it seems alright, however, i get an exception:

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)

请告知我错过了。

推荐答案

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

With Gson (assuming that you have on object {...} on the top level of your json file):

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。使用类似于:


In response to your comment:

You should certainly avoid re-parsing the json from a string. Use something like:

... 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!
   }

} 

这篇关于如何解析JSON文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆