Quantcast
Channel: User Sinatr - Stack Overflow
Viewing all articles
Browse latest Browse all 613

Answer by Sinatr for How to serialize properties into separate Json using System.Text.Json in C#?

$
0
0

You can use json converters to customize produced json and perform custom steps (creating separate json-files in your case).

Just to get you started, here is a converter:

public class XConverter : JsonConverter<X>{    public required string FileName { get; init; }    public override X? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) =>        JsonSerializer.Deserialize<X>(File.ReadAllText(reader.GetString()));    public override void Write(Utf8JsonWriter writer, X value, JsonSerializerOptions options)    {        writer.WriteStringValue(FileName);        File.WriteAllText(FileName, JsonSerializer.Serialize(value));    }}

To pass file name into converter you need to create attribute yourself:

[AttributeUsage(AttributeTargets.Property)]public class JsonXConverterAttribute : JsonConverterAttribute{    public required string FileName { get; init; }    public override JsonConverter? CreateConverter(Type typeToConvert)    {        if (typeToConvert != typeof(X))            throw new NotSupportedException("Attribute is only applicable to property of X type");        return new XConverter { FileName = FileName };    }}

Now you can use attribute in your class:

public class A{    [JsonXConverter(FileName = "X1.json")]    public X X1 { get; set; }    [JsonXConverter(FileName = "X2.json")]    public X X2 { get; set; }    [JsonXConverter(FileName = "X3.json")]    public X X3 { get; set; }}

And to test we serialize and deserialize:

A a = ... (your code)var json = JsonSerializer.Serialize(a);Debug.WriteLine(json);var b = JsonSerializer.Deserialize<A>(json);Debug.WriteLine(JsonSerializer.Serialize(b.X1));Debug.WriteLine(JsonSerializer.Serialize(b.X2));Debug.WriteLine(JsonSerializer.Serialize(b.X3));

The output:

10:48:54:929    {"X1":"X1.json","X2":"X2.json","X3":"X3.json"}10:48:54:929    {"LargeList":[{"AnotherList":["placeholder"]}]}10:48:54:929    {"LargeList":[{"AnotherList":["dummy"]}]}10:48:54:929    {"LargeList":[{"AnotherList":["text"]}]}

And there should be 3 json-files near executable file.


Viewing all articles
Browse latest Browse all 613

Latest Images

Trending Articles



Latest Images

<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>