在C#中使用JSON.NET反序列化多维JSON的正确方法 [英] Proper way to deserialize multidimensional JSON using JSON.NET in C#

查看:180
本文介绍了在C#中使用JSON.NET反序列化多维JSON的正确方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在研究如何反序列化此json文件:

I was researching during a lot of time about how deserialize this json file:

{  
"clients":[  
  {  
     "id":"a0ece5db-cd14-4f21-812f-966633e7be86",
     "name":"Britney",
     "email":"britneyblankenship@quotezart.com",
     "role":"admin"
  },
  {  
     "id":"e8fd159b-57c4-4d36-9bd7-a59ca13057bb",
     "name":"Manning",
     "email":"manningblankenship@quotezart.com",
     "role":"admin"
  },
  {  
     "id":"a3b8d425-2b60-4ad7-becc-bedf2ef860bd",
     "name":"Barnett",
     "email":"barnettblankenship@quotezart.com",
     "role":"user"

     [ ... ]

这是我的控制器代码:

 using (var sr = new StreamReader(response.GetResponseStream()))
{
    receivedData = sr.ReadToEnd();
}

var userList = JsonConvert.DeserializeObject<List<User>>(receivedData);

foreach (User us in userList)
{
   //this method just print the user Id
   MsgBox(u.Id);
}

因此,我绝对会因为Json

So, I am absolutely stuck because the Json

JsonConvert.DeserializeObject>(receivedData);启动 以下例外:

JsonConvert.DeserializeObject>(receivedData); launch the following exception:

Newtonsoft.Json.JsonSerializationException:'无法反序列化 当前的JSON对象(例如{"name":"value"}) 'System.Collections.Generic.List`1 [InsuranceWebAPI.Models.User]' 因为该类型需要JSON数组(例如[1,2,3])进行反序列化 正确.

Newtonsoft.Json.JsonSerializationException: 'Cannot deserialize the current JSON object (e.g. {"name":"value"}) into type 'System.Collections.Generic.List`1[InsuranceWebAPI.Models.User]' because the type requires a JSON array (e.g. [1,2,3]) to deserialize correctly.

我尝试将json数据设置为数组和列表,但不起作用. 我知道这可能是一个非常初学者的问题,但是我不习惯与Json和Json.net合作

I try to set the json data into an array and a list, but doesn't works. I know that maybe is a very beginner question but I am not used to work with Json and Json.net

任何机构都可以帮助我将数据获取到数组或列表中.

Can any body help me to get the data into an array or List.

在此先感谢大家,如果无法正确理解有关Json.net的其他问题,我们深表歉意.

Thanks in advance to everybody and sorry if I don't understand properly the other questions about Json.net

推荐答案

这是因为您的JSON格式不是用户集合.它是一个对象,其中包含名为clients的属性,该属性是用户的集合.看到这个模型:

That is because your JSON format is not of a collection of users. It is of an object containing a property named clients which is a collection of users. See this model:

public class RootObject
{
    public IEnumerable<User> clients { get; set; }
}
public class User
{
    public string id { get; set; }
    public string name { get; set; }
    public string email { get; set; }
    public string role { get; set; }
}

并通过执行以下操作:

var data = JsonConvert.DeserializeObject<RootObject>(File.ReadAllText(receivedData));

这篇关于在C#中使用JSON.NET反序列化多维JSON的正确方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆