{
"token": "d10e",
"@version": "1",
"key": "30a8-e2dc2c6c7a5e",
"result": [
["name :Customer10", "description :Hesco"],
["name :Customer16", "description :IoTLab"],
["name :Customer32", "description :Abdevand"],
["name :Customer20", "description :Jahad Daneshgahi KNU"],
["name :Customer8", "description :Babinab"],
["name :Customer4", "description :ISA"],
["name :ParsIoT", "description :customer created on 2018-01-16T05:45:05.939 (BSS Time)"],
["name :Customer18", "description :Customer18"]
]
}
我如何反序列化为json数组?
C#返回错误,无法反序列化此json !!!
var resp = JsonConvert.DeserializeObject<List<Organization>>(response);
这是组织类,如何列出结果对象
public class Organization
{
[JsonProperty("token")]
public string token { get; set; }
[JsonProperty("@version")]
public string version { get; set; }
[JsonProperty("@timestamp")]
public string timestamp { get; set; }
[JsonProperty("type")]
public string type { get; set; }
[JsonProperty("result")]
public Result[] result { get; set; }
}
这是Result类:
public class Result
{
[JsonProperty("name")]
public string name { get; set; }
[JsonProperty("description")]
public string description { get; set; }
}
答案 0 :(得分:3)
您有两个问题:
List<Organization>
,但您的JSON仅代表单 Organization
。result
属性是由字符串数组组成的数组-JSON不包含任何“名称”或“描述”属性,仅包含类似于“名称:Customer20”的值等。这是起作用的完整示例:
using System;
using System.IO;
using Newtonsoft.Json;
public class Organization
{
[JsonProperty("token")]
public string Token { get; set; }
[JsonProperty("@version")]
public string Version { get; set; }
[JsonProperty("key")]
public string Key { get; set; }
[JsonProperty("result")]
public string[][] Results { get; set; }
}
class Program
{
static void Main(string[] args)
{
string json = File.ReadAllText("test.json");
var org = JsonConvert.DeserializeObject<Organization>(json);
Console.WriteLine($"Token: {org.Token}");
Console.WriteLine($"Version: {org.Version}");
Console.WriteLine($"Key: {org.Key}");
Console.WriteLine("Result entries:");
foreach (string[] entry in org.Results)
{
Console.WriteLine(string.Join(", ", entry));
}
}
}
但是现在您需要分别解析result
数组中的每个条目。 (如果您可以修改JSON的格式,则最好将每个条目都作为一个对象,但是上面的代码将按照您介绍的方式处理JSON。)