【发布时间】:2019-05-08 09:30:36
【问题描述】:
将 json 嵌套对象反序列化为类属性而不是类对象
我只想让 json 反序列化器直接反序列化到我的 FlatClassModel,而不是将其序列化到 ClassModel,然后手动映射
以下面的代码为例
using System;
using System.Collections.Generic;
using System.Linq;
using Newtonsoft.Json.Linq;
using Newtonsoft.Json;
public class Program
{
public static void Main()
{
// assume we have a given json
var Json = @"{
'ClassLevelProperty': 'Class Level Values',
'NestedModel': {
'FirstNestedProperty': 'First Nested value',
'AnotherNestedProperty': 'Another Nested Value'
}
}";
var classModel = JsonConvert.DeserializeObject<ClassModel>(Json);
var flatclassModel = JsonConvert.DeserializeObject<FlatClassModel>(Json);
Console.Write(classModel.ClassLevelProperty + " ... " + classModel.NestedModel.FirstNestedProperty + " ... " + classModel.NestedModel.AnotherNestedProperty);
Console.WriteLine();
Console.Write(flatclassModel.ClassLevelProperty + " ... " + flatclassModel.FirstNestedProperty + " ... " + flatclassModel.AnotherNestedProperty);
}
}
class ClassModel
{
public string ClassLevelProperty { get; set; }
public NestedModel NestedModel { get; set; }
}
public class NestedModel
{
public string FirstNestedProperty { get; set; }
public string AnotherNestedProperty { get; set; }
}
public class FlatClassModel
{
public string ClassLevelProperty { get; set; }
public string FirstNestedProperty { get; set; }
public string AnotherNestedProperty { get; set; }
}
提示:尝试将代码转到 https://try.dot.net/ 粘贴并运行的便捷方法
【问题讨论】:
-
好吧,这主要是为了解析发送网格事件并希望将它们存储在一个 DatabaseTable 中,所以对我来说在一个操作中完成它而不是反序列化然后映射是有意义的(可能有很多数据处理),@CodeCaster 这有意义吗?
-
您可以使用来自Can I specify a path in an attribute to map a property in my class to a child property in my JSON? 的
JsonPathConverter解决方案。有关工作示例,请参阅小提琴 here。
标签: c# json json.net deserialization