【发布时间】:2014-04-23 00:41:58
【问题描述】:
我有一个非常简单的类,用于将 JSON 字符串反序列化为字典
private static Dictionary<string,string> DeserializeJSON(string json)
{
var dict = new Dictionary<string,string>();
if (string.IsNullOrEmpty(json))
return dict;
var jsDict = JsonConvert.DeserializeObject<Dictionary<string,string>>(json);
if (jsDict != null)
dict = jsDict;
return dict;
}
这确实反序列化了字符串,但是当字符串包含空值时终止,例如
["ImplementID",null,"ImplementType","Flexicoil Airseeder","SeedUnits","Kg/H","SeedApplicationRate","75","CropType","Wheat(Morombi)","Fertiliser0ID","2edd3043","FertiliserRate0","100","FertiliserRateUnit0","Kg/H"]
具有以下回归
2014-04-23 01:39:07.212 myapp[63857:70b] 哎呀,有些东西突然出现:无法将当前 JSON 数组(例如 [1,2,3])反序列化为“System.Collections.Generic”类型。 Dictionary`2[System.String,System.String]' 因为该类型需要一个 JSON 对象(例如 {"name":"value"})才能正确反序列化。 要修复此错误,请将 JSON 更改为 JSON 对象(例如 {"name":"value"})或将反序列化类型更改为数组或实现集合接口的类型(例如 ICollection、IList),例如可以从 JSON 数组反序列化。 JsonArrayAttribute 也可以添加到类型中以强制它从 JSON 数组反序列化。 路径'',第 1 行,位置 1.- 在 Newtonsoft.Json.Serialization.JsonSerializerInternalReader.EnsureArrayContract (Newtonsoft.Json.JsonReader 阅读器,System.Type objectType,Newtonsoft.Json.Serialization.JsonContract 合同)[0x00000] 在:0 在 Newtonsoft.Json.Serialization.JsonSerializerInternalReader.CreateList (Newtonsoft.Json.JsonReader reader, System.Type objectType, Newtonsoft.Json.Serialization.JsonContract contract, Newtonsoft.Json.Serialization.JsonProperty member, System.Object existingValue, System.String id ) [0x00000] 在 :0 在 Newtonsoft.Json.Serialization.JsonSerializerInternalReader.CreateValueInternal (Newtonsoft.Json.JsonReader reader, System.Type objectType, Newtonsoft.Json.Serialization.JsonContract contract, Newtonsoft.Json.Serialization.JsonProperty member, Newtonsoft.Json.Serialization.JsonContainerContract containerContract, Newtonsoft.Json.Serialization.JsonProperty containerMember, System.Object existingValue) [0x00000] in :0 在 Newtonsoft.Json.Serialization.JsonSerializerInternalReader.Deserialize (Newtonsoft.Json.JsonReader reader, System.Type objectType, Boolean checkAdditionalContent) [0x00000] in :0
在反序列化 JSON 字符串时,有没有一种简单的方法可以忽略空值(和键)?
【问题讨论】:
标签: c# json serialization json.net