Tirtha R
Tirtha R

Reputation: 1318

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

Upvotes: 0

Views: 959

Answers (3)

victor
victor

Reputation: 812

This worked for me:

    string json = "{\"INIT\": [\"string\", \"string\"], \"QUIT\": [\"string\", \"string\", \"string\"], \"SYN\": [ [\"string\", \"string\", \"string\", \"string\"],[\"string\", \"string\", \"string\", \"string\", \"string\"],[\"string\", \"string\", \"string\"]]}";
    Dictionary<string, object> convert = new JavaScriptSerializer().Deserialize<Dictionary<string, object>>(json);

Upvotes: 0

Lali
Lali

Reputation: 2866

Use Newtonsoft library and the following method

String[] strArray = JsonConvert.DeserializeObject<string[]>(jsonArray);

Upvotes: 1

MikeS
MikeS

Reputation: 1764

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"]}
    ]
}

Upvotes: 2

Related Questions