C
Join ServerC#
help
Newtonsoft JsonConverter to replicate the serialization of the JsonObjectAttribute on an IEnumerable
AAlexicon12/11/2022
Can someone help me create a Newtonsoft.Json.JsonConverter that will write an IEnumerable the same way one is written if the class has the JsonObjectAttribute?
For example, given this class:
I need the result from this:
To look like this:
Doing the above works fine if the class has the JsonObjectAttribute on it like this:
However without the JsonOjectAttribute the result will look like this:
But I cannot use the attribute since I do not own the class I am trying to serialize in this way, Thus I need to write a converter to do this same thing but I am struggling to figure out how.
I tried googling this but I could not find any similar examples and everyone just seems to suggest using the JsonObject attribute, which I can't and do not want to use.
Any assistance would be appreciated.
For example, given this class:
public class MyEnumerable<T> : IEnumerable<T>
{
public int TotalCount { get; set; }
public IEnumerable<T> Values { get; set; }
public IEnumerator<T> GetEnumerator() => Values.GetEnumerator();
Enumerator IEnumerable.GetEnumerator() => GetEnumerator();
}
I need the result from this:
var me = new MyEnumerable<string>
{
TotalCount = 2,
Values = new List<string>
{
"a",
"b"
}
}
JsonConvert.SerializeObject(obj, Formatting.Indented);
To look like this:
{
"TotalCount": 2,
"Values": [
"a",
"b"
]
}
Doing the above works fine if the class has the JsonObjectAttribute on it like this:
[JsonObject]
public class MyEnumerable<T> : IEnumerable<T>
{
...
}
However without the JsonOjectAttribute the result will look like this:
[
"a",
"b"
]
But I cannot use the attribute since I do not own the class I am trying to serialize in this way, Thus I need to write a converter to do this same thing but I am struggling to figure out how.
I tried googling this but I could not find any similar examples and everyone just seems to suggest using the JsonObject attribute, which I can't and do not want to use.
Any assistance would be appreciated.
AAlexicon12/11/2022
Additionally I wish I could use System.Text.Json but it doesn’t seem like it will work either until this issue is resolved: https://github.com/dotnet/runtime/issues/63791
AAccord12/12/2022
Looks like nothing has happened here. I will mark this as stale and this post will be archived until there is new activity.