我想将此 JSON 返回从 php 文件转换为 c#。但作为新手不知道如何,请帮助。
{"response": [
{"user_id":"26","crtloc_lat":"47.678238","crtloc_lng":"-122.131416"},
{"user_id":"27","crtloc_lat":"9.350192","crtloc_lng":"-95.391006"},
{"user_id":"28","crtloc_lat":"47.678238","crtloc_lng":"-122.131416"}
]}
上面的 JSON 是从我的 PHP 文件返回的。
WebRequest request = WebRequest.Create("http://localhost/abh/returntest.php");
WebResponse response = await request.GetResponseAsync();
List<Response> json ;
using (var stream = new StreamReader(response.GetResponseStream()))
{
json = JsonConvert.DeserializeObject<List<Response>>(stream.ReadToEnd());
}
foreach (var item in json)
{
Console.WriteLine("id={0},latitude={1},longitude={2}",item.user_id,item.crtloc_lat,item.crtloc_lng);
}
我正在使用的类是:
public class Response
{
public string user_id { get; set; }
public string crtloc_lat { get; set; }
public string crtloc_lng { get; set; }
}
public class RootObject
{
public List<Response> response { get; set; }
}
我收到这个错误:
Cannot deserialize the current JSON object (e.g. {"name":"value"}) into type 'System.Collections.Generic.List`1[afterall.Response]' because the type requires a JSON array (e.g. [1,2,3]) to deserialize correctly.
最佳答案
根据您的示例 JSON,以下行是错误的。
json = JsonConvert.DeserializeObject<List<Response>>(stream.ReadToEnd());
尝试将其更改为:
json = JsonConvert.DeserializeObject<RootObject>(stream.ReadToEnd());
编辑:
WebRequest request = WebRequest.Create("http://localhost/abh/returntest.php");
WebResponse response = await request.GetResponseAsync();
RootObject json;
using (var stream = new StreamReader(response.GetResponseStream()))
{
json = JsonConvert.DeserializeObject<RootObject>(stream.ReadToEnd());
}
foreach (var item in json)
{
Console.WriteLine("id={0},latitude={1},longitude={2}",item.user_id,item.crtloc_lat,item.crtloc_lng);
}
关于c# - json转c#反序列化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33013828/