首页 > 解决方案 > C# JsonConvert.DeserializeObject 没有正确填充对象

问题描述

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

缩进器.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; }
}

标签: c#jsonasp.net-mvcparsingjson-deserialization

解决方案


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

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

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

您可以在页面https://jsonlint.com上验证 josn ,您会看到验证将失败。如果您引入更改我建议验证是可以的!


推荐阅读