可序列化属性导致API使用ReadAsAsync返回空属性

时间:2018-12-06 17:29:02

标签: c# serialization

我需要序列化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]的情况下它们可以正常工作。有解决办法吗?

StarShip

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

1 个答案:

答案 0 :(得分:0)

在将[JsonObject]属性添加到StarShip类之后,此方法有效