简体   繁体   中英

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);
   }

在此处输入图片说明

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

使用Newtonsoft库和以下方法

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

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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM