【发布时间】:2015-09-24 13:19:11
【问题描述】:
我无法将 JSON 对象转换为 C# 类对象我尝试了很多方法,但弹出相同的错误:
无法反序列化当前 JSON 对象(例如 {"name":"value"}) 输入类型 'System.Collections.Generic.List`1[CoderwallDotNet.Api.Models.Account]' 因为该类型需要一个 JSON 数组(例如 [1,2,3])来反序列化 正确。
我正在使用这个 JSON 并在 windows 8.1 应用程序中获取响应。
[
{
"id": 1,
"time": 40,
"srcLong": 35.909124,
"srcLat": 31.973628,
"destLong": 35.898258,
"destLat": 31.985622,
"subSites": [
{
"id": 1,
"name": "location1"
},
{
"id": 2,
"name": "location2"
},
{
"id": 3,
"name": "locaion3"
}
]
}]
我尝试使用 webclient 从 JSON 读取,但它无法识别它,所以我使用 Newtonsoft.Json 并创建了这些类来获取响应。
public class SubSite
{
public int id { get; set; }
public string name { get; set; }
}
public class RootObject
{
public int id { get; set; }
public int time { get; set; }
public double srcLong { get; set; }
public double srcLat { get; set; }
public double destLong { get; set; }
public double destLat { get; set; }
public List<SubSite> subSites { get; set; }
}
var serviceUri = "http://localhost:24728/api/sites";
var client = new HttpClient();
var response = await client.GetAsync(serviceUri);
var datafile = await response.Content.ReadAsStringAsyn();
List<RootObject> data = JsonConvert.DeserializeObject<List<RootObject>>(datafile);
test1234.Text = data.ToString();//i am trying to for eample destlat
但我无法获得我得到响应的价值,一切都很好,但我不知道如何将它放入对象并在我想要的任何地方使用它。例如,我想获取时间值和其他值,但我对子站点列表有问题,或者获取子站点内的位置或srclong 或srclat,这是如何将 Json 获取到 c# 对象的项目:
https://onedrive.live.com/?cid=e648f5a0f179f346&id=E648F5A0F179F346%218429&ithint=folder,rar&authkey=!ALKlJdwsb8ER2FA
【问题讨论】:
-
顺便说明一下:它的拼写是 JSON (JavaScript Object Notation),但发音像“Jason”:)
-
鉴于错误有:
System.Collections.Generic.List``1[CoderwallDotNet.Api.Models.Account]我认为您没有显示正确的代码或正确的错误。 -
我已对您的条款进行了一些修改; C# 类是 POCO。 JSON 只是 JSON,它不能是 POCO,因为 POCO 代表 Plain Old CLR Object。 JSON 对 CLR 一无所知。
-
序列化的意义在于。
-
System.Collections.Generic.List``1[CoderwallDotNet.Api.Models.Account] sry 来自我在网上发现的其他帖子它是同样的错误运行代码,你会看到它为什么我会分享这个项目?因为我真的需要帮助,这才是真正的项目
标签: c# asp.net json windows-8.1 poco