在c#中,如何用多个嵌套数组建模JSON对象
本文关键字:数组 嵌套 建模 JSON 对象 何用多 | 更新日期: 2023-09-27 18:17:36
我正在从我正在连接的系统中获得此JSON响应,并试图找出将其反序列化为c#对象的最佳方法。我目前正在使用RestSharp,它看起来很容易使用,但JSON的格式让我有点困惑。下面是输入的格式:
[
{"name": "Tickets:",
"schema": [
{"dataType": "string", "colName": "First", "idx": 0},
{"dataType": "string", "colName": "Second", "idx": 1},
{"dataType": "string", "colName": "Name", "idx": 2}
],
"data": [
["bill", "test", "joe"],
["bill2", "test2", "joe2"],
["bill3", "test3", "joe3"]
]
}
]
下面是我当前的代码:
var url = "http://myUrl:10111";
var client = new RestClient { BaseUrl = url };
var request = new RestRequest { Method = Method.GET, Resource = "/search?fmt=Json", RequestFormat = DataFormat.Json };
request.AddHeader("accept", "application/json");
var response = client.Execute(request);
var wptResponse = new JsonDeserializer().Deserialize<TicketResults>(response);
return wptResponse;
,但如上所述,我试图找出正确的方法来建模TicketResults对象,以支持上述消息的反序列化。
理想情况下,我想要这样的东西:
public class TicketResults
{
public List<Ticket> Tickets {get;set;}
}
public class Ticket
{
public string First {get;set;}
public string Second {get;set;}
public string Name {get;set;}
}
和在上面的示例中将获得Tickets集合中的三个条目。
另外,上面的JSON格式是否正常,因为我从来没有见过它被分解成单独的模式和数据部分(我可以看到它可能节省一些空间,但在这种情况下,消息不是那么大)
在Visual Studio 2012及以上版本中,您可以进入Edit > Paste Special > Paste JSON as classes
。根据从剪贴板粘贴的示例,它生成以下代码。
public class Rootobject
{
public Class1[] Property1 { get; set; }
}
public class Class1
{
public string name { get; set; }
public Schema[] schema { get; set; }
public string[][] data { get; set; }
}
public class Schema
{
public string dataType { get; set; }
public string colName { get; set; }
public int idx { get; set; }
}
string json = File.ReadAllText("json.txt");
Rootobject root = new Rootobject();
root.Property1 = JsonConvert.DeserializeObject<Class1[]>(json);
我同意json格式相当…高飞。下面是如何建模您的dto:
public class JsonDto
{
public string name { get; set; }
public Schema[] schema {get; set;}
public string[][] data { get; set; }
}
public class Schema
{
public string dataType { get; set; }
public string colName { get; set; }
public int idx { get; set; }
}
我能够得到你的字符串(未更改)与JSON反序列化。像这样:
var jsonDto = JsonConvert.DeserializeObject<JsonDto[]>(json);
您对返回的JSON的结构有任何控制吗?这有点古怪。由于某种原因,字段名和数据是分开的。如果格式更合理一些,比如:
[
{
"First": "bill",
"Second": "test",
"Name": "joe"
},
{
"First": "bill2",
"Second": "test2",
"Name": "joe2"
},
]
那么您将有机会将它序列化到您的Ticket类。但是,如果不修改JSON结构(我不建议您这样做),您要序列化的c#类将不得不匹配JSON结构。
我想你可以想出一个中间类来保存JSON数据。然后可以循环遍历这些对象,并从中创建Ticket类的实例。这样至少可以得到一个可以使用的数据结构。