【问题标题】:Deserialize Json Nested Object to a class level property instead of a class object [duplicate]将Json嵌套对象反序列化为类级别属性而不是类对象[重复]
【发布时间】: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/ 粘贴并运行的便捷方法

【问题讨论】:

标签: c# json json.net deserialization


【解决方案1】:

我只想让 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; }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-12-21
    • 1970-01-01
    • 2021-12-08
    • 1970-01-01
    • 2018-03-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多