如何反序列化 Json 数组以列出(或)数组

How to Deserialize Json Array to list (or) Array

我正在从 Ajax 调用中获取数据,其给出的 json 输出如下所述 在我的代码隐藏 Jobsheet 参数中有 json 数组对象 如何在反序列化中传递该参数并从中获取值

这是我的 Json 输出:

string Jobsheet =[{"var_name_data":"Demo1Demo2Demo3Demo4Demo5Demo6Demo7Demo8Demo9Demo10 1,2,3,4,5,6,7,8,9,10"}]

我的Class:

 public class RootObject
{
    public List<User> var_name_data { get; set; }
}

public class User
{
    public string first_name { get; set; }
    public int customer_id { get; set; }
}

在我的代码隐藏中:

   [WebMethod]
    [ScriptMethod(ResponseFormat = ResponseFormat.Json)]
    public static object Details4(string selectedJobSheet)
    {

        try
        {
            var des = (RootObject)Newtonsoft.Json.JsonConvert.DeserializeObject(selectedJobSheet, typeof(RootObject));

            return des.var_name_data.Count.ToString();


        }
        catch (Exception)
        {

            throw;
        }

    }

它抛出异常:

An exception of type 'Newtonsoft.Json.JsonSerializationException' occurred in EBCheckList.dll but was not handled in user code Additional information: Cannot deserialize the current JSON array (e.g. [1,2,3]) into type 'EBCheckDAL.RootObject' because the type requires a JSON object (e.g. {"name":"value"}) to deserialize correctly. To fix this error either change the JSON to a JSON object (e.g. {"name":"value"}) or change the deserialized type to an array or a type that implements a collection interface (e.g. ICollection, IList) like List that can be deserialized from a JSON array. JsonArrayAttribute can also be added to the type to force it to deserialize from a JSON array. Path '', line 1, position 1. occurred

请帮我把上面的json数据转换成列表(或)元素数组

您可以将 Jobsheet 反序列化为对象列表而不是 RootObject,如以下代码:
1 - 创建与 json 对象匹配的对象:

public class User
{
    public string Var_name_data { get; set; }
}

2 - 反序列化 Jobsheet:

string Jobsheet = @"[{""var_name_data"":""Demo1Demo2Demo3Demo4Demo5Demo6Demo7Demo8Demo9Demo10 1,2,3,4,5,6,7,8,9,10""}]";

List<User> users = JsonConvert.DeserializeObject<List<User>>(Jobsheet);

演示

foreach(User user in users)
{
    Console.WriteLine(user.Var_name_data);
}
// or
Console.WriteLine(users.count);

结果

Demo1Demo2Demo3Demo4Demo5Demo6Demo7Demo8Demo9Demo10 1,2,3,4,5,6,7,8,9,10
//or
1

希望对您有所帮助。