如何在C#中解析JSON对象

5
我收到以下JSON数据:
[{"id":"1","text":"System Admin","target":{"jQuery1710835279177001846":12},"checked":true,"state":"open"},
{"id":"2","text":"HRMS","target":{"jQuery1710835279177001846":34},"checked":false,"state":"open"},
{"id":"3","text":"SDBMS","target":{"jQuery1710835279177001846":42},"checked":false},
{"id":"8","text":"Admin","target":{"jQuery1710835279177001846":43},"checked":false},
{"id":"9","text":"My test Admin","target":{"jQuery1710835279177001846":44},"checked":false,"state":"open"},
{"id":"24","text":"ModuleName","target":{"jQuery1710835279177001846":46},"checked":false,"state":"open"}]

尝试使用Json.Net和强类型解析以下内容:

这是我的属性类:

public class testclass
    {
        public string id { get; set; }
        public string text { get; set; }
        public string @checked { get; set; }
        public string state { get; set; }
        public target jQuery1710835279177001846 { get; set; }

    }
    public class testclass2
    {
        public List<testclass> testclass1 { get; set; }

    }

    public class target
    {
        public string jQuery1710835279177001846 { get; set; }
    }

我在尝试访问数据时遇到了异常。

Cannot deserialize the current JSON array (e.g. [1,2,3]) into type 'QuexstERP.Web.UI.Areas.SysAdmin.Controllers.testclass' because the type requires a JSON object (e.g. {"name":"value"}) to deserialize correctly.

我的控制器代码如下:
 public void Test(string Name, object modeldata)
        {

            var obj = JsonConvert.DeserializeObject<testclass>(Name);

        }

有没有想法如何在C#中解决这个问题?
3个回答

8

你的Json字符串中似乎包含了序列化的数组对象,因为它包含了[ ]。这意味着你有一个Json字符串,它是由数组对象序列化而成的。所以你需要将其反序列化为数组对象,尝试使用以下代码:

var obj = JsonConvert.DeserializeObject<List<testclass>>(jsonString);

3
您有一个 TestClass 数组。因此应该像这样写:
var model= JsonConvert.DeserializeObject<List<testclass>>(Name);

为什么要使用JSonConvert?在MVC3中,您可以像这样做:
return Json(yourmodel,JsonRequestBehavior.AllowGet);

我想从视图获取数据到服务器端。 - Rahul Rajput

1
你的JSON对象是这样的。
{
      "id":"1",
      "text":"System Admin",
      "target":{
         "jQuery1710835279177001846":12
      },
      "checked":true,
      "state":"open"
}

应该像这样,我猜

{
      "id":"1",
      "text":"System Admin",
      "jQuery1710835279177001846":12,
      "checked":true,
      "state":"open"
}

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