【发布时间】:2017-12-18 14:18:57
【问题描述】:
我正在反序列化这样的第三方字符串:
{"status":4,"errors":[{"Duplicate Application":"Duplicate Application"}]}
我使用我的标准扩展方法:
public static T DeserializeJson<T>(string response)
where T : class
{
var s = new DataContractJsonSerializer(typeof(T));
try {
using (var ms = new MemoryStream()) {
byte[] data = System.Text.Encoding.UTF8.GetBytes(response);
ms.Write(data, 0, data.Length);
ms.Position = 0;
return (T)s.ReadObject(ms);
}
}
catch {
return default(T);
}
}
我试图反序列化的类如下所示:
[DataContract]
public class ResponseProps
{
[DataMember(Name = "status", Order = 0)]
public string ResponseCode { get; set; }
[DataMember(Name = "lead_id", Order=1)]
public string LeadId { get; set; }
[DataMember(Name = "price", Order=2)]
public decimal Price { get; set; }
[DataMember(Name = "redirect_url", Order = 3)]
public string RedirectUrl { get; set; }
[DataMember(Name = "errors", Order = 4)]
public List<Dictionary<string, string>> Errors { get; set; }
}
我在 Errors 属性中使用了 Dictionary (string, string) 类型的 List,因为我尝试过的其他类型已经破坏了反序列化器 - 这使得序列化器不再抛出异常。
但是,我现在正在尝试从错误中检索数据 - 我正在使用以下代码:
var cr = XmlHelper.DeserializeJson<ResponseProps>(response);
var errorStore = new HashSet<string>();
foreach (var dict in cr.Errors)
{
foreach (var kvp in dict)
{
errorStore.Add(kvp.Key + ": " + kvp.Value);
}
}
我已经进行了各种测试 - dict 计数为 1,但没有 kvp,所以当循环运行时我没有收到任何消息。
我猜这又是由于反序列化而不是不正确的循环,但我无法修复它。
有人有什么建议吗?
【问题讨论】:
-
我无法控制字符串中的内容。
-
如果您在 c# 4.0 中工作,因此无法使用
UseSimpleDictionaryFormat,那么其中一些答案可能会有所帮助:SerializeDictionary<TKey, TValue>to JSON with DataContractJsonSerializer。 -
但是如果没有,你可以切换到json.net 甚至
JavaScriptSerializer吗?是否需要使用DataContractJsonSerializer?
标签: c# json serialization datacontractjsonserializer