Search code examples
c#jsonjson-deserialization

How to de-serialize JSON array of array of strings in C#


I have the following JSON format.

{
    "INIT": ["string", "string"],
    "QUIT": ["string", "string", "string"],
    "SYN": [
        ["string", "string", "string", "string"],
        ["string", "string", "string", "string", "string"],
        ["string", "string", "string"]
    ]
}

I am using the following C# class template,

[DataContract]
public class TemplateClass
{
    [DataMember(Name = "INIT")]
    public string[] init;

    [DataMember(Name = "QUIT")]
    public string[] quit;

    [DataMember(Name = "SYN")]
    public Synonym[] synonyms;
}


[DataContract]
public class Synonym
{
    [DataMember]
    public string[] words;
}

When I run the following code, it doesn't de-serialize the strings in 'SYN'. Please refer to the image below.

using (StreamReader reader = new StreamReader(jsonFilePath))
   {
      DataContractJsonSerializer jsonSerializer = new DataContractJsonSerializer(typeof(TemplateClass));
      dataObject = (TemplateClass) jsonSerializer.ReadObject(reader.BaseStream);
   }

enter image description here


Solution

  • Your JSON has SYN as an array of an array of strings where you are defining it in c# as an array of objects of type 'Synonym' but not specifying a property. You could define synonyms as a string[][] or change your JSON to include the property name words so:

    {
        "INIT": ["string", "string"],
        "QUIT": ["string", "string", "string"],
        "SYN": [
           {"words": ["string", "string", "string", "string"]},
            {"words":["string", "string", "string", "string", "string"]},
           {"words":["string", "string", "string"]}
        ]
    }