Deserializing json Nested Objects to class properties instead of a class object
well I just want json deserializer do deserialize directrly to my FlatClassModel
instead of serializing it to the ClassModel
and then map it by hand
look at the following code for example
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; }
}
Tip: A handy way to try the code goto https://try.dot.net/ paste and run