【问题标题】:Parsing jsonobject when entire json is an array?当整个json是一个数组时解析jsonobject?
【发布时间】:2016-02-12 22:02:51
【问题描述】:

我为此使用 gson-2.5。这两个json的格式略有不同,在第一个;

"usethis": [
    {
      "id": 111,
      "text": "some text that i would like",
    },
  {
      "id": 222,
      "text": "someothertextiwouldlike",
    }
]

我会以这种方式解析它以获取“文本”,一切都会好起来的;

JsonParser jp = new JsonParser();
        JsonElement root = jp.parse(listcontents);
        JsonObject rootobj = root.getAsJsonObject();

        JsonArray items = rootobj.get("usethis").getAsJsonArray();
        for(int i = 0; i < items.size(); i++) {
            JsonObject item = items.get(i).getAsJsonObject();
            String thetext = item.get("text").getAsString();
            System.out.println("text: " + thetext  + "\n");
            }

不同之处在于,在第二个中,我没有任何东西可以作为根对象,这与第一个使用“usethis”不同;

[
  {
      "id": 111,
      "text": "some text that i would like",
    },
  {
      "id": 222,
      "text": "someothertextiwouldlike",
    }
]

和设置

rootobj.get("usethis").getAsJsonArray();

rootobj.get("").getAsJsonArray();

只是给我一个错误。我将如何解析第二个 json?

【问题讨论】:

  • 嗯,你自己看到了,第二个JSON不是JSON对象。只需将其解析为数组即可...
  • @fge 如果我理解正确,我也这样做了,让我将其添加到问题中。
  • @fge 好的,忘记我刚才说的话!它确实是这样工作的。这是我忽略的另一件事。我的错。谢谢。

标签: java json parsing gson


【解决方案1】:

JsonElement 只是 JsonArray 和 JsonObject 的超类。

JsonArray items = root.getAsJsonArray();

应该做你想做的。

【讨论】:

    猜你喜欢
    • 2015-09-10
    • 2015-10-16
    • 1970-01-01
    • 1970-01-01
    • 2017-10-17
    • 1970-01-01
    • 1970-01-01
    • 2020-11-15
    相关资源
    最近更新 更多