JSONAPI Complex attributes

212 views Asked by At

Is this sample in a correct format based on JSON API specifications? In another word can we have in attributes an array?

{
  "meta": {
  },
  "links": {
    "self": ""
  },
  "jsonapi": {
    "version": "",
    "meta": {
    }
  },
  "data": {
    "type": "typeof(class)",
    "id": "string",
    "attributes": [
      {
        "item1": "Value1",
        "item2": "Value2",
        "item3": "Value3"
      }
    ],
    "links": {
      "self": ""
    }
  }
}

I am not sure even after reading that (link) If correct how can I Deserialize it I am using JSONAPISerializer package in C#

2

There are 2 answers

0
jelhan On BEST ANSWER

Your example is invalid.

The value of the attributes key in a resource object must be an attributes object. It must not be an array as in your example:

7.2.2.1 Attributes

The value of the attributes key MUST be an object (an “attributes object”). Members of the attributes object (“attributes”) represent information about the resource object in which it’s defined.

https://jsonapi.org/format/#document-resource-object-fields

The value of a specific attribute may be a complex data structure:

Attributes may contain any valid JSON value, including complex data structures involving JSON objects and arrays.

But that would be something different than the example you have given. It would look like this instead:

{
  "data": {
    "type": "typeof(class)",
    "id": "string",
    "attributes": {
      "foo": [
        {
          "item1": "Value1",
          "item2": "Value2",
          "item3": "Value3"
        }
      ]
    ]
  }
}

In the example given above foo would be an attribute, which has a complex data structure as a value.

8
SNBS On

Why aren't you sure? Here's a quote from JSON API specification:

Attributes may contain any valid JSON value, including complex data structures involving JSON objects and arrays.

Class System.Text.Json.JsonSerializer can deserialize a JSON array into a C# IEnumerable<T>. So you may create an object that has a property Attributes of type IEnumerable<T> and deserialize like this:

using System.IO;
using System.Text.Json;

// ...

string json = File.ReadAllText("YourJsonDocumentPath");

YourEntityDescribedInJsonDocument obj = JsonSerializer.Deserialize<YourEntityDescribedInJsonDocument>(json, new JsonSerializerOptions());