CSharp · Console
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Reflection;
using System.Text.Json;
using System.Text.Json.Serialization;
using NUnit.Framework; // Throws NUnit.Framework.AssertionException
//https://stackoverflow.com/questions/64201481/what-is-the-difference-if-any-between-the-jsonrequired-and-jsonpropertyreq
public class Thing {
public int Id { get; set; }
public string Name { get; set; }
[JsonConverter(typeof(UnsafeRawJsonConverter))]
public string Data { get; set; } // JSON Data
}
/// <summary>
/// Serializes the contents of a string value as raw JSON. The string is validated as being an RFC 8259-compliant JSON payload
/// </summary>
public class RawJsonConverter : JsonConverter<string>
{
public override string Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
{
using var doc = JsonDocument.ParseValue(ref reader);
return doc.RootElement.GetRawText();
}
protected virtual bool SkipInputValidation => false;
public override void Write(Utf8JsonWriter writer, string value, JsonSerializerOptions options) =>
// skipInputValidation : true will improve performance, but only do this if you are certain the value represents well-formed JSON!
writer.WriteRawValue(value, skipInputValidation : SkipInputValidation);
}
/// <summary>
/// Serializes the contents of a string value as raw JSON. The string is NOT validated as being an RFC 8259-compliant JSON payload
/// </summary>
public class UnsafeRawJsonConverter : RawJsonConverter
{
protected override bool SkipInputValidation => true;
}
class TestClass
{
public static void Test()
{
Test("{\"key\":\"value\"}");
Test(@"[
[[""aa"",2,[],{}]]]");
Test("true");
Test(null);
Assert.Throws<JsonException>(()=> Test("Foo"));
}
public static void Test(string data)
{
var thing = new Thing
{
Id = 1,
Name = "Thing",
Data = data,
};
var json = JsonSerializer.Serialize(thing, new JsonSerializerOptions { WriteIndented = true });
Console.WriteLine(json);
var thing2 = JsonSerializer.Deserialize<Thing>(json);
Console.WriteLine(thing2.Data);
Assert.AreEqual(data, thing2.Data);
}
}
public class Program
{
public static void Main()
{
Console.WriteLine("Environment version: {0} ({1})", System.Runtime.InteropServices.RuntimeInformation.FrameworkDescription, Environment.Version);
Console.WriteLine("System.Text.Json version: " + typeof(JsonSerializer).Assembly.FullName);
Console.WriteLine();
try
{
TestClass.Test();
}
catch (Exception ex)
{
Console.WriteLine("Failed with unhandled exception: ");
Console.WriteLine(ex);
throw;
}
}
}