c# - json转c#反序列化

标签 c# php json

我想将此 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/

相关文章:

c# - 如果 1 列包含相同数据,SQL 追加其他列

php - 跨多个字段的搜索查询,包括 JOIN

php - Database_Exception [2]:mysqli_connect():服务器向客户端发送了未知的字符集(255)。请向开发商报告

android - 从适配器中的字符串获取 Android 资源 ID

javascript - 在 C# 中解析 JSON 文件 (Unity)

c# - json.net Schema IsValid 慢

c# - 获取嵌套属性及其父项的全名

c# - 禁用 asp 图像按钮

c# - 进程不会在表单关闭时终止

php - MySQL 就像在一行上一样,就像在多行 INNER JOINED 表上一样