【问题标题】:Convert Generic API Response in Blazor在 Blazor 中转换通用 API 响应
【发布时间】:2021-09-14 20:19:55
【问题描述】:

我正在开发一个 Blazor WASM 项目,但我被困在这一点上。

我正在使用 DataAccess 服务向 EndPoints 发出请求;

端点返回一个ResultList,这是一个需要在客户端解析的通用对象。对象定义:

public class ResultList
    {
        public ResultList(List<object> resultados, string codigoErro = null, string mensagemErro = null)
        {
            this.Resultados = resultados;
            this.CodigoErro = codigoErro;
            this.MensagemErro = mensagemErro;
        }

        public string MensagemErro { get; set; }
        public List<object> Resultados { get; set; }
        public string CodigoErro { get; set; }
    }

在客户端,我收到相同的类型:

 public async Task<ResultList> GetEmpresas()
        {
            try
            {
                ResultList Result = await _httpClient.GetFromJsonAsync<ResultList>("api/EmpCadBasico/GetEmpresas");
                return Result;
            }
            catch (Exception ex)
            {
                return new ResultList(null, null, ex.Message);
            }

        }

问题是:我无法将List&lt;Object&gt; 转换为其他类型,例如List&lt;Empresa&gt;。 C# 编译不会通知错误,但在执行时会发生。

我试过Serialize和Deserialize,还是不行:

public async Task GetEmpresas()
        {
            ResultList Resultado = await _dataAccess.GetEmpresas();

            if (await RetornoOk(Resultado))
            {
                string x = JsonSerializer.Serialize(Resultado.Resultados); // Here, that's fine.
                List<Empresa> y = JsonSerializer.Deserialize<List<Empresa>>(x); // Here, it finds the objects, but all of them with null values.
            }
        }

X 值:'[{"id":1,"nomeEmpresa":"Alamo","cnpj":"00072619000101","dataCadastro":"2020-01-01T00:00:00","colaborador":[],"marca":[]}]'

Y 值:Y value after Deserialization

【问题讨论】:

    标签: serialization blazor asp.net-core-webapi blazor-webassembly


    【解决方案1】:

    根据你提供的json返回数据,我做了如下还原,成功返回数据,你可以参考一下。

    型号:

    public  class TestModel
        {
            public int id { get; set; }
            public string nomeEmpresa { get; set; }
           public string cnpj { get; set; }
            public string dataCadastro { get; set; }
    
            public List<colaborador> colaborador { get; set; }
    
            public List<marca> marca { get; set; }
    
        }
    
        public class colaborador
        {
            public int id { get; set; }
            public string test { get; set; }
        }
    
        public class marca
        {
        public int id { get; set; }
        public string test { get; set; }
    }
    

    然后我给各个属性赋值,结果如下:

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-11-20
      • 2017-01-14
      • 2022-01-06
      • 2020-11-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多