将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/粘贴并运行的便捷方法
答案 0 :(得分:0)
我只希望json反序列化器直接对我的FlatClassModel反序列化
为什么?该模型必须匹配JSON才能成功反序列化。假设AnotherNestedProperty
位于根级别和的更深级别,那么您想填充哪一个?为什么呢?
因此,要么创建从一种类型到另一种类型的转换:
var flattened = new FlatClassModel
{
ClassLevelProperty = classModel.ClassLevelProperty,
FirstNestedProperty = classModel.NestedModel.FirstNestedProperty,
AnotherNestedProperty = classModel.AnotherNestedProperty,
};
或创建只读属性:
public class ClassModel
{
public string ClassLevelProperty { get; set; }
public string FirstNestedProperty => NestedModel.FirstNestedProperty;
public string AnotherNestedProperty => NestedModel.AnotherNestedProperty;
public NestedModel NestedModel { get; set; }
}