簡體   English   中英

可序列化屬性導致API使用ReadAsAsync返回空屬性

[英]Serializable Attribute causes API to return null properties with ReadAsAsync

我需要序列化StarShip對象,因此添加了[Serializable]屬性。 沒有這個我嘗試序列化時出現錯誤

public static byte[] ObjectToByteArray(this object obj)
{
    if (obj == null)
        return null;
    var bf = new BinaryFormatter();
    using (var ms = new MemoryStream())
    {
        bf.Serialize(ms, obj);
        return ms.ToArray();
    }
}

但是,當我使用

HttpResponseMessage.ReadAsAsync<SWAPIResponse<StarShip>>();

現在,所有StarShip屬性都為null ,在沒有[Serializable]情況下它們可以正常工作。 有針對這個的解決方法嗎?

飛船

//[Serializable]
public class StarShip : SWAPIEntity
{
    public static string rootUrl { get; } = "starships";

    public string MGLT { get; set; }
    public string Cargo_Capacity { get; set; }
    public string Consumables { get; set; }
    public string Cost_In_Credits { get; set; }
    public string Crew { get; set; }
    public string Edited { get; set; }
    public string Hyperdrive_Rating { get; set; }
    public string Length { get; set; }
    public string Manufacturer { get; set; }
    public string Max_Atmosphering_Speed { get; set; }
    public string Model { get; set; }
    public string Passengers { get; set; }
    //public Film[] films { get; set; }
    //public Pilot[] pilots { get; set; }
    public string Starship_Class { get; set; }
    public string Url { get; set; }
}

SWAPIResponse

public class SWAPIResponse<T> where T : SWAPIEntity
{
    public int count { get; set; }
    public string next { get; set; }
    public string previous { get; set; }
    public T[] results { get; set; }
}

這是我實際調用ReadAsAsync

private static async Task<SWAPIResponse<T>> GetResult<T>(string url) 
    where T : SWAPIEntity
{
    using (var client = new HttpClient())
    {
        var response = await client.GetAsync(url);
        var result = await response.Content.ReadAsAsync<SWAPIResponse<T>>();
        return result;
    }
}

[JsonObject]屬性添加到StarShip類后,此方法起作用

暫無
暫無

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

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