JSON数组转换为通用列表,但无法转换为通用集合。为什么?

6

我将从客户端 Web 应用程序发送一个 Json 数组到 ASP.NET WebAPI。例如,

{
    "SurveyId":3423,
    "CreatorId":4235,
    "GlobalAppId":34,
    "AssociateList":[
        {"AssociateId":4234},
        {"AssociateId":43},
        {"AssociateId":23423},
        {"AssociateId":432}
    ],
    "IsModelDirty":false,
    "SaveMode":null
}

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

使用以下代码,我将响应发布到WebApi:

public IEnumerable<Associate> Post(ResponseStatus responseStatus)
{
   return this.responsestatusrepository.ResponseStatusCheck(responseStatus);               
}

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; }
}

作为我的代码分析纠正的一部分,我已经将List<>更改为Collection<>。 例如:public Collection<Associate> AssociateList { get; set; }

但是,在使用集合而不是列表时,它总是得到一个null值。这是否有任何特定的原因?


1
请尝试使用IEnumerable <Associate>,或查看此链接(http://stackoverflow.com/questions/15071120/how-to-pass-an-object-array-to-webapi-list)可能会有所帮助。 - Kishor
1个回答

0

好的,我认为我需要以间接的方式回答这个问题。您传递给服务器的是一个对象数组(JSON格式),但一旦您在C#中开始处理它,对象数组现在被视为单个C#对象。在此对象内,您的模型希望其中一个字段是Associate的集合。

没错,在处理类似于本例中提到的JSON数据时,我更喜欢使用Newtonsoft的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; }
}

制作了一个程序,它接受字符串(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>();
}

现在当我调用这个方法并传递与您提供的完全相同的JSON数据时,我得到了这个:

Breakpoint after method ran

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

祝你好运!


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接