简体   繁体   中英

GSON deserialization of object arrays

I have a class with the following attributes

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

Now I want GSON to deserialize/map a json document to it. It works well, except for my lists - they are empty. The json document looks as follows (snippet):

"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/"
    },

The mapping works, even for the single instance of

JenkinsServerView primaryView

but not for the Lists. I'm starting the mapping this way:

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

looks your json data that you are trying to parse is invalid.

In your json jobs and views are arrays and both of them doesn't have the closing brace at the end.

The valid json will be as follows: (Observe the closing braces at the end of the array)

{
    "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/"
        }
    ]
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM