As a newcomer to .NET, I’m learning to work with JSON deserialization in C#. How can I efficiently deserialize a JSON array of objects with nested properties into a list of C# instances, while effectively handling the de-nesting process?
I have a JSON array representing a list of objects with nested properties, like this:
[
{"name":"apple","properties":{"color":"red","flavor":"sweet"}},
{"name":"orange","properties":{"color":"orange","flavor":"sour"}}
]
I want to deserialize this JSON into a list of C# objects. The C# class looks like this:
public class Fruit
{
public string Name { get; set; }
public string Color { get; set; }
public string Flavor { get; set; }
}
It’s important to note that the structure of the C# object (Fruit) differs from the structure of the JSON object. In particular, the C# object does not have a "properties" variable.
Is there a more efficient way to achieve this than manually iterating through the JSON array elements and assigning values to Fruit objects?
My Code:
using System;
using System.Collections.Generic;
using System.Text.Json;
public class Fruit
{
public string Name { get; set; }
public string Color { get; set; }
public string Flavor { get; set; }
}
class Program
{
static void Main()
{
string json = "[{"name":"apple","properties":{"color":"red","flavor":"sweet"}},{"name":"orange","properties":{"color":"orange","flavor":"sour"}}]";
// Deserialize into a list of Fruit objects
List<Fruit> fruits = new List<Fruit>();
var options = new JsonSerializerOptions
{
PropertyNameCaseInsensitive = true
};
var jsonObjects = JsonSerializer.Deserialize<List<JsonElement>>(json, options);
foreach (var jsonObject in jsonObjects)
{
var fruit = new Fruit
{
Name = jsonObject.GetProperty("name").GetString(),
Color = jsonObject.GetProperty("properties").GetProperty("color").GetString(),
Flavor = jsonObject.GetProperty("properties").GetProperty("flavor").GetString()
};
fruits.Add(fruit);
}
// Print the fruits
foreach (var fruit in fruits)
{
Console.WriteLine("Name: " + fruit.Name);
Console.WriteLine("Color: " + fruit.Color);
Console.WriteLine("Flavor: " + fruit.Flavor);
Console.WriteLine();
}
}
}
2
Answers
You have several ways of doing it. i think i would use a custom converter for this because:
The shortest way (in one code line)
or you can wrap this code in a converter