CSharp · Console
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Runtime.Serialization.Formatters;
using System.IO;
using System.Data;
using System.ComponentModel.DataAnnotations;
using System.Globalization;
using System.Reflection;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using Newtonsoft.Json.Converters;
using Newtonsoft.Json.Serialization;
using NUnit.Framework; // Throws NUnit.Framework.AssertionException
//https://stackoverflow.com/questions/54341115/jobject-tostring-with-stringenumconverter-not-working
public enum ErrorCode
{
A,
B,
C
}
class TestClass
{
public static void Test()
{
var response = JObject.FromObject(
new
{
Error = new
{
Message = "Test",
Code = ErrorCode.A
}
},
JsonSerializer.CreateDefault(new JsonSerializerSettings { Converters = { new StringEnumConverter() } })
)
.ToString(Formatting.None);
Console.WriteLine(response);
// Now try serializing to JObject without StringEnumConverter. Note that the value of
// Error.Code will be of type System.Int32
var obj = JObject.FromObject(
new
{
Error = new
{
Message = "Test",
Code = ErrorCode.A
}
},
JsonSerializer.CreateDefault(new JsonSerializerSettings { })
);
Console.WriteLine(obj.SelectToken("Error.Code"));
Console.WriteLine(((JValue)obj.SelectToken("Error.Code")).Value.GetType());
// Here's an example of using a JsonConverter that applies to primitives with ToString()
var convertedJson = obj.ToString(Formatting.None, new PrefixingStringConverter("converter prefix: "));
Console.WriteLine(convertedJson);
}
static string GetJson()
{
var json = @"
";
return json;
}
}
public class PrefixingStringConverter : JsonConverter
{
// Taken from this answer https://stackoverflow.com/a/46797460/3744182
// To https://stackoverflow.com/questions/46788778/how-to-deserialize-dodgy-json-with-improperly-quoted-strings-and-missing-brack
readonly string prefix;
public PrefixingStringConverter(string prefix)
{
this.prefix = prefix;
}
public override bool CanConvert(Type objectType)
{
return objectType == typeof(string);
}
public override bool CanRead { get { return false; } }
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
{
throw new NotImplementedException();
}
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
{
var s = (string)value;
writer.WriteValue(prefix + s);
}
}
public class Program
{
public static void Main()
{
Console.WriteLine("Environment version: " + Environment.Version);
Console.WriteLine("Json.NET version: " + typeof(JsonSerializer).Assembly.FullName);
Console.WriteLine();
try
{
TestClass.Test();
}
catch (Exception ex)
{
Console.WriteLine("Failed with unhandled exception: ");
Console.WriteLine(ex);
throw;
}
}
}