简体   繁体   English

如何将json反序列化为C#列表对象

[英]How to deserialize json into C# List Object

I seem to be running into an issue where I try to deserialize a json array into a C# list (I'm using Json.NET). 我似乎遇到了一个问题,我尝试将json数组反序列化为C#列表(我正在使用Json.NET)。 The problem is I'm getting an error: 问题是我遇到错误:

Cannot deserialize the current JSON array (eg [1,2,3]) into type 'ProjectName.WebServices.EventWebMethods+ServiceItem' because the type requires a JSON object (eg {"name":"value"}) to deserialize correctly. 无法将当前JSON数组(例如[1,2,3])反序列化为类型'ProjectName.WebServices.EventWebMethods + ServiceItem',因为该类型需要JSON对象(例如{“ name”:“ value”})才能正确反序列化。 To fix this error either change the JSON to a JSON object (eg {"name":"value"}) or change the deserialized type to an array or a type that implements a collection interface (eg ICollection, IList) like List that can be deserialized from a JSON array. 要解决此错误,可以将JSON更改为JSON对象(例如{“ name”:“ value”}),也可以将反序列化类型更改为数组,或者将实现集合接口的类型(例如ICollection,IList)更改为List,例如List从JSON数组反序列化。 JsonArrayAttribute can also be added to the type to force it to deserialize from a JSON array. 还可以将JsonArrayAttribute添加到类型中,以强制其从JSON数组反序列化。 Path '[0]', line 1, position 2. 路径“ [0]”,第1行,位置2。

This is my json code which is created by taking a javascript array and using JSON.stringify on it: 这是我的json代码,它是通过采用javascript数组并在其上使用JSON.stringify创建的:

[["6249","Locked"],["6250","Locked"],["6251","Locked"]]

This is the C# code I am using: 这是我正在使用的C#代码:

    [Serializable]
    public class ServiceItem
    {
        long lngId{ get; set; }
        string strStatus{ get; set; }

        public ServiceItem() { }
    }

    [WebMethod(EnableSession = true)]
    public string Create(string strJSON)
    {
        //Error happens on this next line:
        List<ServiceItem> ServiceData = JsonConvert.DeserializeObject<List<ServiceItem>>(strJSON);
        return "test";
    }

How do I get this to deserialize into the C# class. 我如何获得此反序列化到C#类中。 Any help is appreciated! 任何帮助表示赞赏!

UPDATE 更新

I made the changes to my javascript so that it includes the variable names as per suggested. 我对JavaScript进行了更改,以便按照建议包含变量名。 Still same error. 还是一样的错误。 Here is the JSON in the C# variable: 这是C#变量中的JSON:

[
[\"lngId\" : \"6249\",\"strStatus\" : \"Locked\"],
[\"lngId\" : \"6250\",\"strStatus\" : \"Locked\"],
[\"lngId\" : \"6251\",\"strStatus\" : \"Locked\"]
]

Are the curly braces that important, and if that is the problem, why doesn't JSON.Stringify do that? 花括号是否很重要,如果这是问题所在,为什么JSON.Stringify不这样做呢?

UPDATE 2 更新2

Figured it out. 弄清楚了。 I needed to create each json item like this: 我需要像这样创建每个json项目:

arrServices.push({"lngId": intServiceID, "strStatus" : "Locked"});

Now it works. 现在可以了。 Thank you for the help! 感谢您的帮助!

Your example JSON represents an array of arrays of strings. 您的示例JSON表示字符串数组的数组。 The JSON that represents the schema represented by your ServiceItem class would look like this: 代表ServiceItem类表示的架构的JSON看起来像这样:

[  
   {  
      "lngID":"6249",
      "strStatus":"Locked"
   },
   {  
      "lngID":"6250",
      "strStatus":"Locked"
   },
   {  
      "lngID":"6251",
      "strStatus":"Locked"
   }
]

You need to serialize your data on the other end differently (so that it matches your class). 您需要对另一端的数据进行序列化(以便与您的类匹配)。 If that is not an option then you are going to have to manually deserialize the JSON on the server: 如果这不是一个选择,那么您将不得不在服务器上手动反序列化JSON:

List<ServiceItem> ServiceData =
    JArray
    .Parse(input)
    .Select(x => x.ToArray())
    .Select(x => new ServiceItem()
        {
            lngId = x[0].Value<int>(),
            strStatus = x[1].Value<String>()
        })
    .ToList();

Or implement a custom JsonConverter . 或实现自定义JsonConverter

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM