【发布时间】:2014-10-29 23:54:24
【问题描述】:
我有一个包含水果列表的字符串。我的 C# 程序不能直接使用 Fruit,它需要将它们转换为 Banana 或 Apple。 json 中的 constructor 属性中包含有关投射它们的信息。
注意:我使用的是 JSON.NET。
这就是我想要实现的目标:
class Fruit{ public string constructor;}
class Banana : Fruit { public int monkey;}
class Apple : Fruit { public string shape;}
string json = @"[
{
""constructor"":""banana"",
""monkey"":1
},
{
""constructor"":""apple"",
""shape"":""round""
}]";
List<Fruit> fruitList = JsonConvert.DeserializeObject<List<Fruit>>(json);
List<Banana> bananaList = new List<Banana>();
List<Apple> appleList = new List<Apple>();
foreach(var fruit in fruitList){
if(fruit.constructor == "banana") bananaList.Add((Banana)fruit); //bug
if(fruit.constructor == "apple") appleList.Add((Apple)fruit); //bug
}
//use bananaList and appleList for stuff
但是,我不能做演员表。有什么办法可以让bananaList 包含json 中所有构造函数属性设置为"banana" 且与appleList 相同的对象?
解决方案:
public static string objToJson(object obj) {
return JsonConvert.SerializeObject(obj, Formatting.Indented, new JsonSerializerSettings {
TypeNameHandling = TypeNameHandling.Auto
});
}
public static T jsonToObj<T>(string str) {
return JsonConvert.DeserializeObject<T>(str, new JsonSerializerSettings {
TypeNameHandling = TypeNameHandling.Auto
});
}
【问题讨论】:
-
创建的对象是水果。类转换适用于 actual 对象,因此 Fruit 不能“更改”为 Banana/Apple - 只有在其他方式下才有效。话虽如此,很可能使用 CustomConverter 来处理这个问题(Json.NET 支持通过
$type恢复类型),其中此类转换器会将每个对象适当地解析为 real Banana/Apple 实例。 -
哇,看看这里:stackoverflow.com/questions/8030538/…(实际上是在搜索“自定义转换器”后的前几声中)
-
讨厌你使用了我的答案但接受了不同的答案?