-1

我无法反序列化这个:

{
   "backup_times":{
      "12":{
         "time":"2012-12-20 11:52:01",
         "status":"T"
      },
      "2":{
         "time":"2012-12-20 11:22:57",
         "status":"T"
      },
      "3":{
         "time":"2012-12-20 11:23:35",
         "status":"T"
      },
      "13":{
         "time":"2012-12-20 11:52:57",
         "status":"T"
      },
      "9":{
         "time":"2012-12-20 11:46:09",
         "status":"T"
      },
      "4":{
         "time":"2012-12-20 11:28:53",
         "status":"T"
      },
      "5":{
         "time":"2012-12-20 11:30:53",
         "status":"T"
      },
      "10":{
         "time":"2012-12-20 11:48:30",
         "status":"T"
      },
      "11":{
         "time":"2012-12-20 11:49:57",
         "status":"T"
      }
   }
}

这种结构是否可以将其转换为自定义类?

这是我目前拥有的当前 java 类,它基本上包含字符串的 hashmap 作为键和 Job 子类作为值:

    public class RestoreDatesJsonReader {
    private HashMap<String, Job> backupTimes;

    public static class Job {
        private String time;
        private String status;
        public String getTime() {
            return time;
        }
        public void setTime(String time) {
            this.time = time;
        }
        public String getStatus() {
            return status;
        }
        public void setStatus(String status) {
            this.status = status;
        }
    }

    public HashMap<String,Job> getBackupTimes() {
        return backupTimes;
    }

    public void setBackupTimes(HashMap<String, Job> backup_times) {
        this.backupTimes = backup_times;
    }
}
4

1 回答 1

1

GSON(默认情况下)依赖于您的 POJO,其变量名称与您的 JSON 对象匹配。

backupTimes将您的对象更改为backup_times,这将正常工作。

您的另一个选择是@SerializedName为您的字段使用注释:

@SerializedName("backup_times") private HashMap<String, Job> backupTimes;

这告诉 Gsonbackup_times在您的 JSON 中映射到backupTimes您的 POJO。

(一旦我有时间回去这样做,就把它从评论移到正确的答案)

Javadoc在这里:http: //google-gson.googlecode.com/svn/tags/1.2.3/docs/javadocs/com/google/gson/annotations/SerializedName.html

于 2012-12-21T05:22:26.727 回答