Skip to content

Instantly share code, notes, and snippets.

@Jozkee
Created April 17, 2020 05:10
Show Gist options
  • Save Jozkee/7b48bd4aadad6bdb3e47f1c244f12326 to your computer and use it in GitHub Desktop.
Save Jozkee/7b48bd4aadad6bdb3e47f1c244f12326 to your computer and use it in GitHub Desktop.
The '$id' and '$ref' metadata properties must be JSON strings. Current token type is 'PropertyName'
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>netcoreapp3.1</TargetFramework>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="System.Text.Json" Version="5.0.0-preview.2.20160.6" />
</ItemGroup>
</Project>
using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
using System.Text.Encodings.Web;
using System.Text.Json;
using System.Text.Json.Serialization;
namespace ConsoleApp30
{
class Program
{
static async System.Threading.Tasks.Task Main(string[] args)
{
string json = @"{
""$id"": ""1"",
""$values"": [
{
""$id"": ""2"",
""location"": ""1"",
""warehouses"": {
""$id"": ""3"",
""$values"": [
{
""$id"": ""4"",
""warehouse"": ""1""
},
{
""$id"": ""5"",
""warehouse"": ""2""
}
]
}
}
]
}";
Stream stream = new MemoryStream(Encoding.UTF8.GetBytes(json));
var opts = new JsonSerializerOptions
{
ReferenceHandling = ReferenceHandling.Preserve,
PropertyNameCaseInsensitive = true,
Encoder = JavaScriptEncoder.Default
};
List<Locations> locations = await JsonSerializer.DeserializeAsync<List<Locations>>(stream, opts);
foreach(Locations location in locations)
{
Console.WriteLine($"Location {location.Location}");
foreach(Warehouses warehouse in location.Warehouses)
{
Console.WriteLine($" Warehouse {warehouse.Warehouse}");
}
}
}
public class Locations
{
public string Location { get; set; }
public List<Warehouses> Warehouses { get; set; }
}
public class Warehouses
{
public string Warehouse { get; set; }
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment