首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >可序列化属性导致API使用ReadAsAsync返回空属性。

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

Stack Overflow用户
提问于 2018-12-06 17:29:02
回答 1查看 260关注 0票数 0

我需要序列化我的StarShip对象,所以我添加了[Serializable]属性。如果没有此操作,则在尝试将其序列化时会出现错误。

代码语言:javascript
复制
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();
    }
}

但是,当我使用

代码语言:javascript
复制
HttpResponseMessage.ReadAsAsync<SWAPIResponse<StarShip>>();

所有的StarShip属性现在都是null,没有[Serializable],它们可以很好地工作。有解决办法吗?

StarShip

代码语言:javascript
复制
//[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

代码语言:javascript
复制
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的地方

代码语言:javascript
复制
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;
    }
}
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2018-12-07 17:00:55

在将[JsonObject]属性添加到StarShip类之后,这种方法就可以工作了。

票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/53656771

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档