我需要序列化我的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;
}
}发布于 2018-12-07 17:00:55
在将[JsonObject]属性添加到StarShip类之后,这种方法就可以工作了。
https://stackoverflow.com/questions/53656771
复制相似问题