如何在C#中反序列化字符串数组的JSON数组

时间:2017-02-21 15:50:14

标签: c# json json-deserialization

我有以下JSON格式。

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

我正在使用以下C#类模板

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

当我运行以下代码时,它不会反序列化'SYN'中的字符串。请参考下图。

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

enter image description here

3 个答案:

答案 0 :(得分:2)

您的JSON将SYN作为字符串数组的数组,您可以在c#中将其定义为“同义词”类型的对象数组,但不指定属性。您可以将同义词定义为字符串[] []或更改您的JSON以包含属性名称单词:

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

答案 1 :(得分:1)

使用Newtonsoft库和以下方法

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

答案 2 :(得分:0)

这对我有用:

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