【问题标题】:Json to Object using Gson使用 Gson 到对象的 Json
【发布时间】:2013-03-16 10:02:00
【问题描述】:

我有一个类 DocumentBO,它具有以下属性 -

public class DocumentBO implements IStorageBO {
   private String aId;
   private String studyId;
   private Map<AlgorithmsEnum, JobIOStatus> status;
   private String text;
   private Collection<Sentence> sentences;

   public String getaId() {
      return aId;
   }
   public void setaId(String aId) {
      this.aId = aId;
   }
   public String getStudyId() {
      return studyId;
   }
   public void setStudyId(String studyId) {
      this.studyId = studyId;
   }
   public Map<AlgorithmsEnum, JobIOStatus> getStatus() {
      return status;
   }
   public void setStatus(Map<AlgorithmsEnum, JobIOStatus> status) {
      this.status = status;
   }
   public String getText() {
      return text;
   }
   public void setText(String text) {
      this.text = text;
   }
   public Collection<Sentence> getSentences() {
      return sentences;
   }
   public void setSentences(Collection<Sentence> sentences) {
      this.sentences = sentences;
   } 
}

AlgorithmsEnum如下-

public enum AlgorithmsEnum {
   SENTIMENT("sentiment"),
   INTENTION("intention"),
   TOPIC("topic"),
   NER("ner"),
   UIMA("uima");

   private final String value;

   private AlgorithmsEnum(String value) {
      this.value = value;
   }

   public String value() {
      return value;
   }

   @Override
   public String toString() {
      return value;
   }

   public static AlgorithmsEnum fromValue(String value) {
      if (value != null) {
         for (AlgorithmsEnum aEnum : AlgorithmsEnum.values()) {
            if (aEnum.value().equals(value)) {
               return aEnum;
            }
         }
      }
      return null;
   }
}

JobIOStatus 也类似。 我可以使用 GSON 使用以下 TypeToken 成功创建一个 JSON 字符串集合

Type type = new TypeToken<Collection<DocumentBO>>() {}.getType();

但是,当我尝试使用 Gson 返回的 JSON 字符串和相同的 TypeToken 重新创建 Collection 对象时,status 哈希映射的键始终返回为 NULL 而值已成功创建。您认为可能是什么问题?

【问题讨论】:

    标签: java json enums gson


    【解决方案1】:

    问题是您在enum 中覆盖了toString()

    如果您查看正在生成的 JSON,您的 Map&lt;AlgorithmsEnum, JobIOStatus&gt; 的键是您正在创建的小写名称。那是行不通的。当您尝试反序列化 JSON 时,Gson 不知道如何从那些重新创建 enum

    如果您删除您的 toString() 方法,它将正常工作。

    或者,您可以在序列化时使用GsonBuilder 中的.enableComplexMapKeySerialization() 方法,这将忽略您的toString() 方法并使用您的enum 值的默认表示生成JSON,这是必需的。

    【讨论】:

      【解决方案2】:

      当键是从对象派生而不是“本机”数据类型时,Gson 序列化 Map 存在“众所周知的”问题。 请使用这个

      GsonBuilder builder = new GsonBuilder();    
      Gson gson = builder.enableComplexMapKeySerialization().create(); 
      Collection<DocumentBO> obj = gson.fromJson(str, type);
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多