C
C#2y ago
Alexicon

Newtonsoft JsonConverter to replicate the serialization of the JsonObjectAttribute on an IEnumerable

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:
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();
}
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);
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"
]
}
{
"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>
{
...
}
[JsonObject]
public class MyEnumerable<T> : IEnumerable<T>
{
...
}
However without the JsonOjectAttribute the result will look like this:
[
"a",
"b"
]
[
"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.
2 Replies
Alexicon
AlexiconOP2y ago
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
GitHub
Developers should have access to System.Text.Json's default interna...
Background and Motivation Currently, the default json converters used for objects and collection types are internal to System.Text.Json. The library uses hardcoded conventions to decide what defaul...
Accord
Accord2y ago
Looks like nothing has happened here. I will mark this as stale and this post will be archived until there is new activity.
Want results from more Discord servers?
Add your server