Json到c#反序列化

本文关键字:反序列化 Json | 更新日期: 2023-09-27 18:16:33

我想将这个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; }
}

我得到这个错误:

不能反序列化当前JSON对象(例如{"name":"value"})into type 'System.Collections.Generic.List ' 1[afterall.Response]'因为该类型需要一个JSON数组(例如[1,2,3])来反序列化正确。

Json到c#反序列化

根据您的示例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);
}   

重写以下行:

json = JsonConvert.DeserializeObject<List<Response>>(stream.ReadToEnd());

json = JsonConvert.DeserializeObject<Response>(stream.ReadToEnd());

从您的帖子评论中的testlink。您的回复不是:

{"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"}
]}

,而不是:

connected{"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连接对象(无论连接是什么)。如果您删除了包装,它应该像@Dietz张贴。