Мне нужно сериализовать мои 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;
}
}