添加链接
link之家
链接快照平台
  • 输入网页链接,自动生成快照
  • 标签化管理网页链接
Collectives™ on Stack Overflow

Find centralized, trusted content and collaborate around the technologies you use most.

Learn more about Collectives

Teams

Q&A for work

Connect and share knowledge within a single location that is structured and easy to search.

Learn more about Teams

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

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)

  • Thanks for contributing an answer to Stack Overflow!

    • Please be sure to answer the question. Provide details and share your research!

    But avoid

    • Asking for help, clarification, or responding to other answers.
    • Making statements based on opinion; back them up with references or personal experience.

    To learn more, see our tips on writing great answers.