JSON数组正在转换为通用列表,但不转换为通用集合.为什么?

Sun*_*nil 6 collections json list asp.net-web-api

我正在从客户端Web应用程序发送一个Json数组到asp.net webapi.例如,

{
    "SurveyId":3423,
    "CreatorId":4235,
    "GlobalAppId":34,
    "AssociateList":[
        {"AssociateId":4234},
        {"AssociateId":43},
        {"AssociateId":23423},
        {"AssociateId":432}
    ],
    "IsModelDirty":false,
    "SaveMode":null
}
Run Code Online (Sandbox Code Playgroud)

这里的Associate List是一个JSON数组,通常它会自动序列化为List <>对象.

使用下面的代码,我将响应发布到WebApi

public IEnumerable<Associate> Post(ResponseStatus responseStatus)
{
   return this.responsestatusrepository.ResponseStatusCheck(responseStatus);               
}
Run Code Online (Sandbox Code Playgroud)

ResponseStatus类如下所示.

public class ResponseStatus : AppBaseModel
{
        public int SurveyId { get; set; }
        public int CreatorId { get; set; }
        public int GlobalAppId { get; set; }
        public List<Associate> AssociateList { get; set; }
}
Run Code Online (Sandbox Code Playgroud)

我已将List <>更改为Collection <>,作为我的代码分析更正的一部分.即public Collection<Associate> AssociateList { get; set; }

但是当我们使用集合而不是List时,它总是得到一个空值.这有什么具体原因吗?

Amu*_*kog 0

好吧,我想我必须以间接的方式回答这个问题。您传递到服务器的是一个对象数组(JSON 格式),但是一旦您开始在 C# 中处理该对象数组,该对象数组现在将被视为单个 C# 对象。在该对象内,您的模型期望其中一个字段是 Associate 的 Collection。

是的,当我处理类似于本例中提到的 JSON 数据时 - 我更喜欢使用 Newtonsofts 的 JOject。

以下是我如何使用您提供的 JSON 数据创建 C# 对象:

使用你的模型:

public class ResponseStatus
{
    public int SurveyId { get; set; }
    public int CreatorId { get; set; }
    public int GlobalAppId { get; set; }
    public Collection<Associate> AssociateList { get; set; }
}

public class Associate
{
    public int AssociateId { get; set; }
}
Run Code Online (Sandbox Code Playgroud)

创建一个例程,它接受字符串(JSON 数据),并返回 ResponseStatus 类型的对象:

using System;
using System.Collections.Generic;
using Newtonsoft.Json.Linq;

---------------------------------------------------------------------

public static ResponseStatus GetResponseStatusObject(string jsonData)
{
    JObject jObject = JObject.Parse(jsonData);
    return jObject.ToObject<ResponseStatus>();
}
Run Code Online (Sandbox Code Playgroud)

现在,当我调用此方法并传递与您提供的完全相同的 JSON 数据时,我得到以下结果:

方法运行后断点

这可能不会直接解决您的问题,但希望能引导您在使用 JavaScript/C# 时理解数组/对象序列化的正确方向。

祝你好运!