C# JsonConvert.DeserializeObject 没有正确填充对象
C# JsonConvert.DeserializeObject does not properly fill object
JsonConvert.DeserializeObject<Language>(json)
returns 属性为空的对象。我想填充 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; }
}
您的 JSON 格式错误,IncreaseIndent
、DecreaseIndent
和 Exception
应该是字符串列表:
{"VBA":[
{ "IncreaseIndent":["Public Sub *","Public Function *",...] },
{ "DecreaseIndent":["End Sub","End Function", ...] },
{ "Exception":["Elseif *","Else","Case *","Case"] }
]}
我在II、DI和Ex后面加了[,每个值后面加了]!
您可以在 https://jsonlint.com 页上验证 josn,您会发现验证将失败。如果引入修改我建议验证就OK了!
JsonConvert.DeserializeObject<Language>(json)
returns 属性为空的对象。我想填充 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; }
}
您的 JSON 格式错误,IncreaseIndent
、DecreaseIndent
和 Exception
应该是字符串列表:
{"VBA":[
{ "IncreaseIndent":["Public Sub *","Public Function *",...] },
{ "DecreaseIndent":["End Sub","End Function", ...] },
{ "Exception":["Elseif *","Else","Case *","Case"] }
]}
我在II、DI和Ex后面加了[,每个值后面加了]!
您可以在 https://jsonlint.com 页上验证 josn,您会发现验证将失败。如果引入修改我建议验证就OK了!