【问题标题】:GSON deserialization of object arrays对象数组的 GSON 反序列化
【发布时间】:2015-01-08 07:36:46
【问题描述】:

我有一个具有以下属性的类

public class JenkinsServer
{
  private String                          url;

  private String                          mode;
  private String                          nodeName;
  private String                          nodeDescription;
  private String                          description;

  private boolean                         useSecurity;
  private boolean                         quietingDown;

  private JenkinsServerView               primaryView;

  private List< JenkinsJob >        jobs;
  private List< JenkinsServerView > views;
}

现在我希望 GSON 将 json 文档反序列化/映射到它。它运作良好,除了我的清单 - 它们是空的。 json文件如下(sn-p):

"jobs": [
{
  "name": "AnotherJob",
  "url": "https://build.example.com/jenkins/job/AnotherJob/",
  "color": "disabled"
},
{
  "name": "AnotherJob2",
  "url": "https://build.example.com/jenkins/job/Build%20CI%20Build/",
  "color": "blue"
},

"views": [
    {
      "name": "-All Views",
      "url": "https://build.example.com/jenkins/view/-All%Views/"
    },
    {
      "name": "Alle",
      "url": "https://build.example.com/jenkins/"
    },

映射有效,即使对于单个实例

JenkinsServerView 主视图

但不适用于列表。我是这样开始映射的:

Gson gson = gsonBuilder.create();
JenkinsServer server = gson.fromJson( reader, JenkinsServer.class );

【问题讨论】:

  • @ashokramcse 不,只是空列表(ArrayList)。
  • 这显然意味着当您将其序列化为 JenkinsServer 类时,您的 JSON 不正确。

标签: java json serialization gson deserialization


【解决方案1】:

看起来您尝试解析的 json 数据无效。

在您的 json 中,jobsviews 是数组,它们最后都没有右大括号。

有效的json如下:(注意数组末尾的右大括号)

{
    "jobs": [
        {
            "name": "AnotherJob",
            "url": "https://build.example.com/jenkins/job/AnotherJob/",
            "color": "disabled"
        },
        {
            "name": "AnotherJob2",
            "url": "https://build.example.com/jenkins/job/Build%20CI%20Build/",
            "color": "blue"
        }
    ],
    "views": [
        {
            "name": "-All Views",
            "url": "https://build.example.com/jenkins/view/-All%Views/"
        },
        {
            "name": "Alle",
            "url": "https://build.example.com/jenkins/"
        }
    ]
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-07-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-08
    相关资源
    最近更新 更多