Looking for a syntax example that uses the JsonArrayAttribute with a c# class or as a JSON deserialization attribute.
I want to remove an explicit List in my current code and see how the JsonArrayAttribute actually works in real code.
Here is my real problem... You can’t google the word “JsonArrayAttribute” because it is within a very common error message. The word shows up on stack overflow in 163 posts. The first 60 of those posts are all about the explicit list deserialization and the error that literally has the word “JsonArrayAttribute” in the error. The solutions are about getting rid of the error with a List– not how to use “JsonArrayAttribute”
It is like I am looking for the opposite of the 90% solution. I actually want to use the “JsonArrayAttribute” attribute in a C# class as a decoration, OR I want to use it as an attribute in a JsonSerializerSettings definition.
I have not seen an example of Json.Net using this property or attribute called “JsonArrayAttribute”.
I understand what JsonArrayAttribute is going to do for me – it is exactly what I need for a test harness situation I am in. I am looking for the syntax or application point to get the Newtonsoft runtime to see the “JsonArrayAtribute”.
From my understanding, the usage itself is actually quite simple. Suppose you implement your own list-like type which for some reason does not inherit from List<T>
and/or doesn't implement IEnumerable
, but still, internally manages a collection of a type matching your json. In this case, you just have to specify [JsonArray]
before the type name, like this:
public class JsonObj
{
// properties
}
[JsonArray]
public class JsonObjCollection
{
// implementation of a list of type JsonObj
}
Then you can do JsonConvert.DeserializeObject<JsonObjCollection>(jsonStr)
instead of i.e. JsonConvert.DeserializeObject<IEnumerable<JsonObj>>(jsonStr)
.
More reading:
Attributes (C#) (Microsoft Docs)
Serialization Attributes and JsonArrayAttribute Class (Json.NET Docs)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With