[英]JSON field values become null after deserialization
I have a JSON string like this 我有一个像这样的JSON字符串
{
"data": {
"id": "f4ba528a54117950",
"type": "password-requests",
"links": {
"self": "https://api.abc.com/api/v2/password-requests/f4ba528a54117950"
},
"attributes": {
"login": "abc",
"type": "agent",
"send-media": false,
"registration-token": "ced84635eba"
}
}
}
My classes are like this 我的课程是这样的
public class SightCallResult
{
public SightCallData data { get; set; }
}
public class SightCallData
{
public string id { get; set; }
public string type { get; set; }
public Dictionary<string, string> links { get; set; }
public AgentAttributes attributes { get; set; }
}
public class AgentAttributes
{
public string Login { get; set; }
public string Type { get; set; }
public bool SendMedia { get; set; }
public string RegistrationToken { get; set; }
}
This is how I deserialize my string 这就是我对字符串进行反序列化的方法
sightCallRslt = JsonConvert.DeserializeObject<SightCallResult>(resultMobileToken);
sightCallData = sightCallRslt.data;
agentAttributes = sightCallData.attributes;
Debug.WriteLine(agentAttributes.RegistrationToken);
But RegistrationToken
is always null. 但
RegistrationToken
始终为null。 But other field values are correctly assigned. 但是正确分配了其他字段值。 Could anybody explain what would be the reason for this.
任何人都可以解释这是什么原因。
I think you are using Newtonsoft.Json
which won't automatically map a hyphenated key name to a PascalCase key name. 我认为您使用的是
Newtonsoft.Json
,它不会自动将带连字符的键名映射到PascalCase键名。
You maybe didn't notice it for eg send-media
because its a non nullable / defaults to false. 您可能没有注意到例如
send-media
因为它不可为空/默认为false。
If you can't change the json, you can decorate the attributes with JsonProperty
: 如果无法更改json,可以使用
JsonProperty
修饰属性:
[JsonProperty(PropertyName="send-media")]
public bool SendMedia { get; set; }
[JsonProperty(PropertyName="registration-token")]
public string RegistrationToken { get; set; }
Either change the type of attributes
to Dictionary<string, object>
, or if you are sure there are a finite amount of possible attributes use the JsonPropertyAttribute
to specify the exact names: 将
attributes
类型更改为Dictionary<string, object>
,或者如果您确定存在有限数量的可能属性,请使用JsonPropertyAttribute
指定确切的名称:
[JsonProperty("registration-token")]
public string RegistrationToken { get; set; }
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.