So, what I want is to serialise and deserialise some JSON using a generic field wrapper class.
I do not want to write some custom JsonConverter class.
I do wish to keep it simple and write some implicit operator type conversion. The following minimal piece of C# code is where I am at now .... just enough to demonstrate the issue and no more. Don't overlook the implicit operators.
using Newtonsoft.Json;
using System;
namespace test
{
public struct SofT<T>
{
[JsonProperty]
public T TValue { get; set; }
public static implicit operator SofT<T>(string jtoken)
{
return new SofT<T>()
{
TValue = (T)Convert.ChangeType(jtoken, typeof(T))
};
}
public static implicit operator string(SofT<T> soft)
{
return soft.TValue?.ToString() ?? "";
}
}
[JsonObject(MemberSerialization.OptIn)]
public class Something
{
[JsonProperty]
public SofT<int> TestStructInt { get; set; }
[JsonProperty]
public SofT<decimal> TestStructDecimal { get; set; }
}
public class Program
{
public void Run()
{
var json = "{ \"TestStructInt\" : \"12\", \"TestStructDecimal\" : \"3.45\"}";
var modelDeserialised = JsonConvert.DeserializeObject<Something>(json);
var modelReserialised = JsonConvert.SerializeObject(modelDeserialised);
Console.WriteLine(modelReserialised);
}
static void Main(string[] args)
{
new Program().Run();
}
}
}
The JSON string is deserialised perfectly. The model object is not reserialised correctly.
The string that is spat out to the console is:
quote {"TestStructInt":{"TValue":12},"TestStructDecimal":{"TValue":3.45}}
The string I expect, or better put want, to be spat out to the console is the same structure in the source JSON, ie:
quote {"TestStructInt":"12"},"TestStructDecimal":"3.45"}}
I am asking for a second pair of eyes to point out my error (and yes I can see the error, the annotation of Value with [JsonProperty], but it seems necessary for default serialisation).