簡體   English   中英

反序列化后,JSON字段值變為null

[英]JSON field values become null after deserialization

我有一個像這樣的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"
    }
  }
}

我的課程是這樣的

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; }
}

這就是我對字符串進行反序列化的方法

sightCallRslt = JsonConvert.DeserializeObject<SightCallResult>(resultMobileToken);
sightCallData = sightCallRslt.data;
agentAttributes = sightCallData.attributes;
Debug.WriteLine(agentAttributes.RegistrationToken);

RegistrationToken始終為null。 但是正確分配了其他字段值。 任何人都可以解釋這是什么原因。

我認為您使用的是Newtonsoft.Json ,它不會自動將帶連字符的鍵名映射到PascalCase鍵名。

您可能沒有注意到例如send-media因為它不可為空/默認為false。

如果無法更改json,可以使用JsonProperty修飾屬性:

        [JsonProperty(PropertyName="send-media")]
        public bool SendMedia { get; set; }
        [JsonProperty(PropertyName="registration-token")]
        public string RegistrationToken { get; set; }

attributes類型更改為Dictionary<string, object> ,或者如果您確定存在有限數量的可能屬性,請使用JsonPropertyAttribute指定確切的名稱:

[JsonProperty("registration-token")]
public string RegistrationToken { get; set; }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM