Search code examples
c#jsonjson-deserialization

Json array with repeating tag


I have the following json:

{
  "OBECT_TAG":
  [
    {
      "PROPERTY1" : "value1",
      "PROPERTY2" : "value2",
    },
    {
      "PROPERTY1" : "value1",
      "PROPERTY2" : "value2",
    },
    {
      "PROPERTY1" : "value1",
      "PROPERTY2" : "value2",
    }
  ]
}

I would like the OBJECT_TAG to be repeated for each object in array. I tried this and deserialization in c# fails. Is it json compliant or what would make it compliant?

{
  [
    "OBECT_TAG":
    {
      "PROPERTY1" : "value1",
      "PROPERTY2" : "value2",
    },
    "OBECT_TAG":
    {
      "PROPERTY1" : "value1",
      "PROPERTY2" : "value2",
    },
    "OBECT_TAG":
    {
      "PROPERTY1" : "value1",
      "PROPERTY2" : "value2",
    }
  ]
}

The reason for this, if necessary, is that the objects get quite large with many levels so when manually editing to be easy to identify where each main object starts while keeping it an array and easy c# object deserialization.

Edit: Is important to keep the root object


Solution

  • Json object has properties with names and values, where value can be another object\array\primitive value.

    Json array contains other objects\arrays\primitives without names.

    Json from your question violates both of the above.

    {
      [...]
    }
    

    Is invalid, because there is no property name. If you want to put array inside object, you have to name it:

    {
        "MyArray": [...]
    }
    

    Then

    [
        "OBECT_TAG":
        {
          "PROPERTY1" : "value1",
          "PROPERTY2" : "value2",
        }
    ]
    

    Is invalid, because array is just a list of unnamed values, and you try to name its entries.

    Closest to what you want I can think of is array of objects, where each object contains named property with tag, and that tag object contains properties:

    [
        { "OBECT_TAG":
          {
            "PROPERTY1" : "value1",
            "PROPERTY2" : "value2"
          }
        }
    ]