C#JsonConvert.DeserializeObject无法正确填充对象

时间:2019-01-06 14:42:26

标签: c# json asp.net-mvc parsing json-deserialization

JsonConvert.DeserializeObject<Language>(json)返回其属性为空的对象。我要填充lang对象,该对象应该具有一些属性,例如名为“ IncreaseIndent”的字符串列表和其他属性。

Indentor.json

{"VBA":[
  { "IncreaseIndent":["Public Sub *","Public Function *","If *then","While *","Do","Do while *","For *","With *","Select Case *","Sub *","Function *","* Type *","Private Sub *","Private Function *","* Enum *"]},
  { "DecreaseIndent":["End Sub","End Function","End if","Wend","Loop While *","Loop","Next","Next *","End With","End Select","End Type","End Enum"] },
  { "Exception":["Elseif *","Else","Case *","Case"]}
]}

C#

public static string FormatCode(string strCode)
{
    Language lang;
    using (StreamReader r = new StreamReader("A:/standardvba/Logic/Indentor.json"))
    {
        string json = r.ReadToEnd();
        lang = JsonConvert.DeserializeObject<Language>(json); //Inside lang every property is null
        return IndentCodePiece(strCode, lang);
    }
}

public class Language
{
    public string ProgrammingLanguage { get; set; }
    public List<string> IncreaseIndent { get; set; }
    public List<string> DecreaseIndent { get; set; }
    public List<string> Exception { get; set; }
}

1 个答案:

答案 0 :(得分:2)

您的JSON格式错误,IncreaseIndentDecreaseIndentException应该是字符串列表:

{"VBA":[
    { "IncreaseIndent":["Public Sub *","Public Function *",...] },
    { "DecreaseIndent":["End Sub","End Function", ...] },
    { "Exception":["Elseif *","Else","Case *","Case"] }
]}

我在II,DI和Ex之后添加了 [,并在每个值的末尾添加了]

您可以在第https://jsonlint.com页上验证josn,您将看到验证将失败。如果您进行更改,我建议验证可以!