xamarin JSON ICollection序列化问题

时间:2017-05-03 20:57:40

标签: xamarin xamarin.forms json.net

我正在尝试将ICollection序列化为JSON,但它将它们序列化为null。

ICollection失败的消息类。

public class Message
{
    [JsonProperty("Id")]
    public Guid MessageId { get; set; }

    [JsonProperty("From")]
    public MessageFrom From { get; set; }

    [JsonProperty("Text")]
    public string Text { get; set; }

    [JsonProperty("Attachments")]
    public ICollection<Attachment> Attachments { get; set; }

    [JsonProperty("AddedTime")]
    public DateTime AddedTime { get; set; }
    public string AddedTimeString { get; set; }
    public string AddedTimeDataString { get; set; }

    [JsonProperty("IsRead")]
    public bool IsRead { get; set; }

    public ChatMyMessageView CV { get; set; }

}

附件类

public class Attachment
    {
        [JsonProperty("Id")]
        public Guid Id { get; set; }

        [JsonProperty("AttachmentType")]
        public AttachmentType Type { get; set; }

        [JsonProperty("Content")]
        public string Content { get; set; }

        [JsonProperty("Thumbnail")]
        public string Thumbnail { get; set; }

        [JsonProperty("AddedDate")]
        public DateTimeOffset AddedDate { get; set; }      

        [JsonIgnore]
        public string Title { get; set; }
    }`

我正在使用正确的参数创建新的Message对象。我在序列化之前仔细检查了附件计数,它总是1或更多。 Here you can see it in debug mode

序列化如下:

        using (var client = new HttpClient(new ModernHttpClient.NativeMessageHandler()))
            {
               client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("bearer", Settings.UserAccessToken);
               var json = await Task.Factory.StartNew(() => JsonConvert.SerializeObject(message, Formatting.None));    
               var content = new StringContent(json, System.Text.Encoding.UTF8, "application/json");
               var response = await client.PostAsync(Urls.SendMessageChat, content);
            }

我接下来的JSON:

{  
   "ChatId":"67ea15e7-c697-473f-8b8a-06be9ee9d72b",
   "isDirectChat":false,
   "Id":"00000000-0000-0000-0000-000000000000",
   "From":null,
   "Text":null,
   "Attachments":[],
   "AddedTime":"0001-01-01T00:00:00",
   "AddedTimeString":null,
   "AddedTimeDataString":null,
   "IsRead":false,
   "CV":null
}

我们可以看到里面没有附件。我做错了什么?我真的不知道为什么这不起作用...请问有人帮助我吗?

1 个答案:

答案 0 :(得分:1)

您能否分享您希望客户提供的实际JSON?

如果您通过浏览器或邮递员/ fiddler点击了网址,那么您获得的确切数据集(json)是什么。

我会尝试几件事

  1. 将数据类型ICollection设为IEnumerableIList
  2. JsonConvert.SerializeObject(message, Formatting.None))

    的行

    var result = await client.GetStringAsync(YOUR_SERVICE_URL) JsonConvert.DeserializeObject<Message>(result)