【问题标题】:Converting a specific JSON to Java Object将特定 JSON 转换为 Java 对象
【发布时间】:2013-07-31 09:53:27
【问题描述】:

我能够使用 Google Gson 将简单的 Json 转换为 java 对象。问题是我无法将这种特定类型的响应转换为 java 对象。我认为这是因为我不确定如何为它实际建模 java 类。以下是Json:

{
"List": {
    "Items": [
        {
            "comment": "comment",
            "create": "random",
            "ID": 21341234,
            "URL": "www.asdf.com"
        },
        {
            "comment": "casdf2",
            "create": "rafsdfom2",
            "ID": 1234,
            "Url": "www.asdfd.com"
        }
    ]
},
"related": {
    "Book": "ISBN",
    "ID": "id"
}}

【问题讨论】:

  • 你能分享你的java类来表示这个Json吗?顺便说一句,这个 json 并不复杂
  • 这就是问题所在。问题是她/他无法弄清楚如何为类建模。我认为。
  • 那里有生成器可以为你生成类。看到这个问题stackoverflow.com/questions/1957406/…

标签: java json object gson


【解决方案1】:

我没有专门使用 Gson,但我在 Jersey 和 JAXB 中使用过 JSON/Java 转换。 我想说翻译 JSON 文本的最简单方法是将每个 {..} 映射到一个类,将 [..] 映射到一个列表。

例如:

Class Data {
    HistoryListClass HistoryList;
    Relation related;
}

Class HistoryListClass {
    List<History> history;
}

Class History {
    String comment;
    String create;
    int ID;
    String ttURL;
}

Class Relation {
    String book;
    String ID;
}

另请参阅: Converting JSON to Java

JSON 代码中的“HistoryList”元素可能应该写成“historyList”,单看给出的代码,我建议您将其更改为直接包含“History”对象列表。

【讨论】:

  • 这个工作正常,但是@Icermanns fields names not identical to the questions 结构。
  • 之后调用“Data data = new Gson().fromJson(inputJsonString, Data.class);
  • 为什么和题目的结构不一样?
  • 此代码不起作用,因为您的类结构中的属性名称必须完全匹配 JSON 字段的名称...所以您需要使用HistoryListID 作为属性的名称...否则您可以使用注解@SerializedName("HistoryList")...
  • 代码已更改为匹配 JSON 格式,尽管名称不符合 Java 命名约定。 MikO 对@SerializedName 的建议听起来不错。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-07-21
  • 2012-08-29
  • 2012-05-29
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多