在WEB API 2接收对象JSON

Receive object JSON in the WEB API 2

如何使用 Web Api 接收对象 json 2. 我正确发送了对象,但在后端我的对象为空。 见下文。

My object JSON

这是我的 JSON 对象,将在请求中发送。

{
    "ItensRateio" : [
        {
            "TipoColetorCusto" : "1",
            "ColetorCusto" : "MRBHAD",
            "Valor": "R$ 25.22",
            "Descricao": "Rateio do Brasil"
        },
        {
            "TipoColetorCusto" : "1",
            "ColetorCusto" : "MRBHAD",
            "Valor": "R$ 25.22",
            "Descricao": "Rateio do Brasil"
        }
    ]
}

My object.

这是我的映射对象。 class 需要用请求中收到的 JSON 对象填充。

public class RateioSimplesRequestModel
{
    List<ItemRateio> ItensRateio { get; set; }
    List<ItemMaterial> ItensMaterial { get; set; }

    public RateioSimplesRequestModel()
    {
        ItensRateio = new List<ItemRateio>();
        ItensMaterial = new List<ItemMaterial>();
    }
}

public class ItemRateio
{
    public string TipoColetorCusto { get; set; }
    public string ColetorCusto { get; set; }
    public string Valor { get; set; }
    public string Descricao { get; set; }
}

public class ItemMaterial
{
    public string CNAE { get; set; }
    public string CodigoMaterial { get; set; }
    public string Descricao { get; set; }
}

My method in the WebAPi 2

[Route("CalcularRateioManual")]
[HttpPost]
public RespostaPadrao<bool> CalcularRateioManual([FromBody] RateioSimplesRequestModel parametro) // THIS OBJECT
{
    RespostaPadrao<bool> retorno = new RespostaPadrao<bool>();
    return retorno;
}

我怎么能这么完美?

您的列表不是 public 并且 json.net 默认情况下仅映射 public 属性。此外,集合不应 public 可设置。

public class RateioSimplesRequestModel
{
    public List<ItemRateio> ItensRateio { get; private set; }
    public List<ItemMaterial> ItensMaterial { get; private set; }

    public RateioSimplesRequestModel()
    {
        ItensRateio = new List<ItemRateio>();
        ItensMaterial = new List<ItemMaterial>();
    }
}

请注意,您在 class...json 对象的 属性 中有 list,因此需要正确格式化并且 parametro 应该发送而不是 ItensRateio

 var parametro = {};
 parametro.ItensRateio = [
   {
     "TipoColetorCusto" : "1",
     "ColetorCusto" : "MRBHAD",
     "Valor": "R$ 25.22",
     "Descricao": "Rateio do Brasil"
   },
   {
     "TipoColetorCusto" : "1",
     "ColetorCusto" : "MRBHAD",
     "Valor": "R$ 25.22",
     "Descricao": "Rateio do Brasil"
   }
 ];

正如 Oliver 所提到的,制作列表 public 应该允许将其转换为对象。

如果您使用的是 C#,验证对象是否可以序列化的一种方法是构造对象并使用 JsonConvert 将其转换为 JSON 等价物.这应该突出显示任何成员保护级别问题,并生成预期的 JSON。

基于上面的类,生成以下JSON:

{
  "ItensRateio": [
    {
      "TipoColetorCusto": "1",
      "ColetorCusto": "MRBHAD",
      "Valor": "R$ 25.22",
      "Descricao": "Rateio do Brasil"
    },
    {
      "TipoColetorCusto": "1",
      "ColetorCusto": "MRBHAD",
      "Valor": "R$ 25.22",
      "Descricao": "Rateio do Brasil"
    }
  ],
  "ItensMaterial": []
}