这是不重复JSON.NET: Deserializing part of a JSON object to a dictionary
我有JSON { “伯爵”:2, “头”:{“itemId”:......,“质量”:......}, “腿”:{“itemId”:......,“质量”:......} }
我需要将其反序列化为字典:IDictionary<GearSlot, Item>
如果我尝试反序列化整个JSON,我会收到错误,因为它无法将"Count:2"
反序列化为<GearSlot, Item>
。
GearSlot
是一个枚举,有~17 +值。这时我已经定义了类:
public class Items {
property Item Head { get; set; }
property Item Legs { get; set; }
...
}
它有效,但不优雅和笨重。
有什么建议吗?
答案 0 :(得分:2)
根据this answer和this answer,您可以deserialize a partial JSON fragment然后重新整合。
var root = JObject.Parse(jsonString);
var serializer = new JsonSerializer();
var expectedResult = serializer.Deserialize<ExpectedType>(root["fragment"].CreateReader());
所以对你来说
var items = new Items {
Head = serializer.Deserialize<Item>(root["Head"])
, Legs = serializer.Deserialize<Item>(root["Legs"])
};
答案 1 :(得分:0)