CSharp · Console
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text.Json;
public class Program
{
public static void Main()
{
var data = @"[
{
""productId"": 1,
""productName"": ""Basic t-shirt"",
""productDescription"": ""a quiet t-shirt"",
""price"": { ""amount"" : 40, ""currency"": ""eur"" },
""attributes"" : [
{
""sizes"": [ ""s"", ""m"", ""l""],
""colors"": [""red"", ""blue"", ""green""]
}]
},
{
""productId"": 2,
""productName"": ""Fancy shirt"",
""productDescription"": ""a loud t-shirt"",
""price"": { ""amount"" : 50, ""currency"": ""eur"" },
""attributes"" : [
{
""sizes"": [ ""s"", ""m"", ""l"", ""xl""],
""colors"": [""ALL"", ""Batique""]
}]
}
]";
//Console.WriteLine(" > json");
//Console.WriteLine(data);
//Console.WriteLine("");
var options = new JsonSerializerOptions() { PropertyNameCaseInsensitive = true };
var products = JsonSerializer.Deserialize<List<ProductCatalogProduct>>(data, options);
if (products.Any(p => !string.IsNullOrEmpty(p.ProductDescription)))
{
foreach (var p in products)
{
Console.WriteLine(p.ProductId + " : " + p.ProductDescription);
}
}
else
{
Console.WriteLine("** json not deserialized **");
}
}
public class Money
{
public string Currency
{
get;
set;
}
public decimal Amount
{
get;
set;
}
public Money(){}
public Money(string currency, decimal amount)
{
Currency = currency;
Amount = amount;
}
}
public class ProductCatalogProduct
{
public int ProductId
{
get;
set;
}
public string ProductName
{
get;
set;
}
public string ProductDescription
{
get;
set;
}
public Money Price
{
get;
set;
}
public List<Attributes> Attributes
{
get;
set;
}
}
public class Attributes
{
public List<string> Sizes
{
get;
set;
}
public List<string> Colors
{
get;
set;
}
}
}