Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JsonArrayAttrribute Usage in C# Code ( Json.Net )

Tags:

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”.

like image 478
Sql Surfer Avatar asked Jul 06 '18 00:07

Sql Surfer


1 Answers

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)

like image 59
Marc.2377 Avatar answered Sep 28 '22 17:09

Marc.2377