将Json嵌套对象反序列化为类级别的属性,而不是类对象

时间:2019-05-08 09:30:37

标签: c# json json.net deserialization

将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/粘贴并运行的便捷方法

1 个答案:

答案 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; }
}
相关问题