我有一个像这样的对象:
public class Foo
{
int bar;
[JsonExtensionData] public Dictionary<string, object> Catchall;
}
和JSON一样:
jsonString = { "bar": "not an int", "dink": 1 }
所以,如果我var foo = JsonConvert.DeserializeObject<Foo>(jsonString)
bar
将无法反序列化为类Foo
,因为它的类型错误,但是是否可以将其插入到[JsonExtensionData] Catchall
字典中?
答案 0 :(得分:0)
您可以使用[JsonIgnore]
标记属性bar
,然后在相应serialization callbacks的Catchall
字典中手动添加和删除其值:
public class Foo
{
const string barName = "bar";
[JsonIgnore]
public int? Bar { get; set; }
[JsonExtensionData]
public Dictionary<string, object> Catchall;
[OnSerializing]
void OnSerializing(StreamingContext ctx)
{
if (Catchall == null)
Catchall = new Dictionary<string, object>();
if (Bar != null)
Catchall[barName] = Bar.Value;
}
[OnSerialized]
void OnSerialized(StreamingContext ctx)
{
if (Catchall != null)
Catchall.Remove(barName);
}
[OnDeserialized]
void OnDeserializedMethod(StreamingContext context)
{
if (Catchall != null)
{
object value;
if (Catchall.TryGetValue(barName, out value))
{
try
{
if (value == null)
{
Bar = null;
}
else
{
Bar = (int)JToken.FromObject(value);
}
Catchall.Remove(barName);
}
catch (Exception)
{
Debug.WriteLine(string.Format("Value \"{0}\" of {1} was not an integer", value, barName));
}
}
}
}
}
请注意,我已将bar
更改为public int? Bar { get; set; }
。 null值表示Bar
的整数值未反序列化,因此,重新序列化时,字典中的值(如果有)不应被属性值取代。