将JSON字符串反序列化为C#

时间:2013-12-21 12:13:13

标签: json serialization asp.net-web-api jsonserializer

我有一个JSON数组,如下所示:

{[
  {
    "personnelId": 201,
    "occupationIds": [
      4,
      5
    ]
  },
  {
    "personnelId": 202,
    "occupationIds": [
      5
    ]
  }
]}

我在ASP.NET Web API控制器中通过JObject收到此字符串:

var jPersonnelAndOccupationIds = json["personnelAndOccupationIds"];

我通过JObject成功地对各种数据结构进行了分类,但这仍然给出RuntimeBinderException,哪种数据结构最适合该JSON字符串,我已经尝试了很多东西,这个IMO是List<PersonnelOccupationsVm>最合适的PersonnelOccupationsVm

public class PersonnelOccupationsVm
    {

        public long personnelId { get; set; }
        public List<long> occupationIds { get; set; }
    }

我这样解密:

var personnelIdsAndOccupationsKvp = jPersonnelAndOccupationIds.ToObject(new List<PersonnelOccupationsVm>());

我试过

System.Web.Script.Serialization.JavaScriptSerializer().Deserialize<List<PersonnelOccupationsVm>>(jPersonnelAndOccupationIds);

既不起作用。任何想法?

修改

根据评论中的要求,我正在这样打电话(有角度):

$http({
  method: 'POST',
  url: '/api/EnterprisePersonnelApi/SubmitOcupationalPersonnel/',
  data: JSON.stringify({ enterpriseId: enterpriseId, positionId: positionId,personnelAndOccupationIds: personnelAndOccupationIds }),
  }).success(function (data, status, headers, config) {
                      deferred.resolve(data);
  }).error(function (data, status, headers, config) {
                     deferred.reject(status);
});

和我的网络API动作:

[System.Web.Http.HttpPost]
public CrudOperationResults SubmitOcupationalPersonnel(JObject jsonData){
dynamic json = jsonData;
var jPersonnelAndOccupationIds = json["personnelAndOccupationIds"];
var personnelIdsAndOccupations = jPersonnelAndOccupationIds.ToObject(new List<PersonnelOccupationsVm>());
.....
}

这给定RunTimeBinderexception,但是当我从.ToString()实例中检索值时调用JObject

var jPersonnelAndOccupationIds = json["personnelAndOccupationIds"].ToString();

和(每个shunty的建议)

var jPersonnelAndOccupationIds = Newtonsoft.Json.JsonConvert.DeserializeObject<List<PersonnelOccupationsVm>>(jPersonnelAndOccupationIds);

这个工作正常,在从JObject中调用我的参数值时添加了前导和尾随花括号,调用.ToString()并按上面反序列化它就可以了。

1 个答案:

答案 0 :(得分:0)

我不是一个特别熟练的Json用户,但是,使用Newtonsoft的东西,我会尝试这样的东西(从LINQPad剪切和粘贴):

void Main()
{
    string json = "[{ \"personnelId\": 201, \"occupationIds\": [4,5]}, {\"personnelId\": 202,\"occupationIds\": [5]}]";

    var js = Newtonsoft.Json.JsonConvert.DeserializeObject<List<PersonnelOccupationsVm>>(json);
    js.Dump();

}

public class PersonnelOccupationsVm
{
    public int PersonnelId { get; set; }
    public List<int> OccupationIds { get; set; }

    public PersonnelOccupationsVm()
    {
        OccupationIds = new List<int>();
    }
}

请注意,我必须修剪源Json中的前导和尾随{}字符。