Let's say I have the following type:
class Foo<T>{
public T data {get;init;}
}
and I want to use this type in multiple controllers:
[HttpPost]
public async void Post(Foo<SomeComplexClass> myFoo){
myFoo.data // this is SomeComplexClass
// Dostuff
}
[HttpPost]
public async void Post2(Foo<OtherMoreDifferentClass>foo2){
foo2.data // this is OtherMoreDifferentClass
}
This is all fine and good, except that the caller of this api which I have no control over serializes T into json before sending the http request, so everything is coming in as Foo<string>
. I'm looking into writing a converter for Foo that's able to take this string and automatically convert it to the requested type by deserializing it to the requested type in the JsonConverter.
I'd like to not have to re-write my controllers or put serialization code in my controllers either
The problem is that the JsonConverter<T>
class requires that you implement read and write using a utf8jsonreader and writer, which are the lowest level apis in the System.Text.Json library. These deal with individual tokens! All I want to do is take the full string that's coming over the wire, serialize it into a Foo<string>
then taking foo.data and re-deserialize it into the requested type if that makes any sense.
Is there a way I can trade this utf8jsonreader for one of the higher level api's somehow? Or is this converter business the wrong approach for this problem?
Update
To clarify, say I have the following class:
public class SomeComplexClass
{
public string Foo { get; set; } = "";
}
Under normal circumstances, it should be serialized as follows:
{"data":{"Foo":"hello"}}
But the caller of my API is sending the following:
{"data":"{\"Foo\":\"hello\"}"}
As you can seem the value of data
has been double-serialized: once to a string, then a second time when the container object is serialized over the wire. I would like to have some automatic way of binding the embedded double-serialized JSON to my Foo<T>.data
value.