C# 反序列化JSON时,值不能为null
我有一个db表,其中有一列内容是以JSON格式存储的,我正在检索JSON,但我得到了这个错误。C# 反序列化JSON时,值不能为null,c#,winforms,json.net,C#,Winforms,Json.net,我有一个db表,其中有一列内容是以JSON格式存储的,我正在检索JSON,但我得到了这个错误。 值不能为null 这是我的代码片段 var stuff = (JObject)JsonConvert.DeserializeObject(commentId); string name = stuff["Name"].Value<string>(); string email = stuff["Email"].Value<string>(); string company =
值不能为null
这是我的代码片段
var stuff = (JObject)JsonConvert.DeserializeObject(commentId);
string name = stuff["Name"].Value<string>();
string email = stuff["Email"].Value<string>();
string company = stuff["Company"].Value<string>();
string phone = stuff["Phone"].Value<string>();
string message = stuff["Message"].Value<string>();
string emails = stuff["Emails"].Value<string>();
我猜当你这么做的时候
string name = stuff["Name"].Value<string>();
string name=stuff[“name”].Value();
而其他的则是获取stuff[“Name”]的值,如果它在JSON中没有该属性,例如,它没有“Name”,则会抛出“value不能为null”
因此,您需要首先检查是否有这些值
你可以这样检查
//check if property exists
if (stuff["Name"].Value<string>()!= null) {
string name = stuff["Name"].Value<string>();
} else {
//there is no "name" property, compensate somehow.
}
//检查属性是否存在
if(stuff[“Name”].Value()!=null){
string name=stuff[“name”].Value();
}否则{
//不存在“名称”属性,请以某种方式进行补偿。
}
假设您的完整JSON如您所示,您的JSON不会为名称和电子邮件提供简单的名称/值对。相反,它有一个索引属性对象的字典,其中每个对象都有一个标签
属性,其值等于所查找属性的名称,以及一个相邻的值
属性和相应的值
您可以通过如下方式构建一个辅助文件,方便地从JSON中获取这些文件:
var dict = JObject.Parse(commentId)
.Descendants()
.OfType<JProperty>()
.Where(p => p.Name == "label")
.ToLookup(p => (string)p.Value, p => (string)p.Parent["value"]); // Use ToLookup because some empty space keys are duplicated
var name = dict["Name*"].SingleOrDefault(); // Notice the asterisk in the property labels.
var email = dict["Email*"].SingleOrDefault();
很老的话题,但我用的是:
string name=stuff[“name”]?.Value()??“未定义”;
字符串email=stuff[“email”]?.Value()??“未定义”代码>
简洁、简单,并提供您自己的默认值。您能提供“commentId”的内容吗?而且它可能不包含姓名、电子邮件、公司或……其中一个值在您的JObject
中不存在。你试过调试你的代码吗?发布你的JObject代码请编辑你的问题并以格式化的格式发布JSON。在我发布代码片段之前,请确认整个JSON是否不在数组中(aka从顶部开始,以{xxx:[
结束,以]}
或只使用and dovar name=(string)东西[“name”]
--这是空安全的。但我得到的是JSON,它具有所有属性。如果你发布JSON,也许我可以提供更多帮助。反序列化可能有问题。“4”:{“标签”:“名称*”,“值”:“Farrukh”,“类型”:“文本”,“验证”:“字母”,“必需”:“1”,“最小值”:“0”,“最大值”:“300”,“工具提示”:“字段0”,自定义“:”,“custom2”:null,“custom3”:“zz”,“custom4”:null,“custom5”:null},“5”:{“label”:“Email*”,“value”:Farrukh@xyx.com“,”类型“:”电子邮件“,”验证“:”电子邮件“,”必填“:”1“,”最小“:”最大“,”工具提示“:”字段1“,”自定义“:”自动回复“,”自定义“:”回复到”是这样的。
var dict = JObject.Parse(commentId)
.Descendants()
.OfType<JProperty>()
.Where(p => p.Name == "label")
.ToLookup(p => (string)p.Value, p => (string)p.Parent["value"]); // Use ToLookup because some empty space keys are duplicated
var name = dict["Name*"].SingleOrDefault(); // Notice the asterisk in the property labels.
var email = dict["Email*"].SingleOrDefault();
Debug.Assert(name == "Farrukh"); // No assert.
Debug.Assert(email == "abc@a.com"); // No assert.