use*_*528 3 .net c# json json.net
我有一个如下所示的 JSON 数据:
{
"Item1": {
"Field1": "Val1",
"Field2": "Val2"
},
"Item2": {
"Field1": "Val11",
"Field2": "Val22"
},
....
"ItemN": {
"Field1": "Val1",
"Field2": "Val2"
},
}
Run Code Online (Sandbox Code Playgroud)
我需要将其反序列化为一组如下所示的类:
public class Root
{
public Item Item1;
public Item Item2;
public List<Item> Items; // << all the Items should go here
}
public class Item
{
public string Field1;
public string Field2;
}
Run Code Online (Sandbox Code Playgroud)
反序列化时如何让 Newtonsoft.Json 以这种方式映射数据?
L.B*_*L.B 11
不需要类Root。我会反序列化为字典
var dict= JsonConvert.DeserializeObject<Dictionary<string, Item>>(json);
Run Code Online (Sandbox Code Playgroud)
如果您需要使用 JSON 中的相同数据填充您的类中显示的Items列表和各个Item属性Root,那么您将需要一个自定义JsonConverter来执行此操作。以下转换器应该可以工作:
public class RootConverter : JsonConverter
{
public override bool CanConvert(Type objectType)
{
return objectType == typeof(Root);
}
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
{
JObject obj = JObject.Load(reader);
var root = new Root();
// populate all known Root properties
serializer.Populate(obj.CreateReader(), root);
// populate Items list with all objects that can be converted to an Item
root.Items = obj.Properties()
.Where(p => p.Value.Type == JTokenType.Object &&
(p.Value["Field1"] != null || p.Value["Field2"] != null))
.Select(p => p.Value.ToObject<Item>())
.ToList();
return root;
}
public override bool CanWrite
{
get { return false; }
}
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
{
throw new NotImplementedException();
}
}
Run Code Online (Sandbox Code Playgroud)
然后要使用它,[JsonConverter]向您的Root类添加一个属性,如下所示:
[JsonConverter(typeof(RootConverter))]
public class Root
{
public Item Item1 { get; set; }
public Item Item2 { get; set; }
public List<Item> Items; // << all the Items should go here
}
Run Code Online (Sandbox Code Playgroud)
小提琴:https : //dotnetfiddle.net/aADhzw
| 归档时间: |
|
| 查看次数: |
526 次 |
| 最近记录: |