【问题标题】:Web API Json DeserialiseWeb API Json 反序列化
【发布时间】:2015-07-10 20:14:40
【问题描述】:

我正在使用 Web Api。

我有一个 A 类型的对象。当我将 A 类型的列表返回给我的客户端,然后使用 Post 方法将 A 类型的列表传回时,JSON 序列化和反序列化会自动完成。

因为我想使用我的 POST 方法传递多个参数,所以我创建了一个包装器对象,其中包含我要传入的每个参数的属性。JSON ser / DeSer 是为这个包装器对象处理的,但是如何做我在包装器对象中反序列化了代表我的类型 A 列表的 JSON?

谢谢。

添加代码:

public class ConfigurationUpdateMessage
{
    public string IpAddress { get; set; }

    public List<object> Configurations { get; set; }
}

Post 方法

  public string PutUpdateConfigurations(ConfigurationUpdateMessage configMessage)   
    {}

客户代码

$scope.UpdateConfigs = function () {

                $.ajax({
                    url: 'api/configurations',
                    dataType: "json",
                    type: "PUT",
                    contentType: 'application/json; charset=utf-8',
                    data: JSON.stringify({ IpAddress: "127.0.0.1", Configurations: $scope.configs }),
                    async: true,
                    processData: false,
                    cache: false,
                    success: function (data) {

                    },
                    error: function (xhr) {

                    }
                });

            };

【问题讨论】:

    标签: c# json asp.net-web-api


    【解决方案1】:

    PRE:你能发布一些代码吗?

    如果您的包装对象包含与序列化对象的类型匹配的属性,模型绑定器应自动将它们反序列化为匹配的属性。除非您发布的 JSON 的结构有问题。

    【讨论】:

    【解决方案2】:

    您应该在服务器端创建相同的包装器类型。

    例如:

    public class OperationDTO
    {
         public string Parameter1 { get; set; }
         public int Parameter2 { get; set; }
         public IEnumerable<A> MyList { get; set; } //List<A> will also work too
    }
    

    您的 Web Api 操作应如下所示:

    [HttpPost]
    public IHttpActionResult Operation([FromBody] OperationDTO)
    {
        //...
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-12-26
      • 2014-04-27
      • 1970-01-01
      • 2021-12-17
      • 1970-01-01
      相关资源
      最近更新 更多