【问题标题】:Gson deserialize Map<K,V> serialized by WCF Rest serviceGson 反序列化由 WCF Rest 服务序列化的 Map<K,V>
【发布时间】:2011-11-17 00:37:04
【问题描述】:

我有 WCF 休息服务。我想在 Android 设备上使用它。为此,我选择了 gson 库。在我想从我的服务对象包含地图返回之前,一切似乎都运行良好。 Gson 将其序列化(并且我假设也尝试从中反序列化)如下:

{"org.Mob.ComplexObject@3dac2f9c":"TAX1","org.Mob.ComplexObject@7369ca65":"TAX2"}

但是我的服务发送的json看起来像:

{"Key":
    {"DefaultValue":"True",
     "Description":null,
     "DisplayName":"Custom Boolean",
     "FieldType":0,
     "Id":6,
     "IsReadOnly":false,
     "IsRequired":false,
     "MaxLength":null,
     "Name":"BoolVal",
     "ParamType":0},
 "Value":"True"},
{"Key":
    {"DefaultValue":"",
     "Description":null,
     "DisplayName":"Custom Text",
     "FieldType":4,
     "Id":7,
     "IsReadOnly":false,
     "IsRequired":true,
     "MaxLength":16,
     "Name":"TextVal",
     "ParamType":0},
 "Value":"sda"}
}

【问题讨论】:

    标签: map gson


    【解决方案1】:

    Gson 没有将 Java 映射序列化为所需格式的 JSON 的内置功能。 (handle complex map keys 的特性没有解决这个问题。)自定义序列化/反序列化处理是必要的。

    【讨论】:

      【解决方案2】:

      另一种方法是添加您自己的 Map / Dictionary 实现,它扩展了 ArrayList,实际上是 KVPair 的列表,其中 KVPair 看起来像:

      class KVPair<K,V>{
          K Key;
          V Value;
      }
      

      我不知道它是否优雅,但它在我的情况下有效。

      【讨论】:

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