leo*_*ora 8 c# parsing json jsonserializer restsharp
我从我连接的系统获取此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"]
]
}
]
Run Code Online (Sandbox Code Playgroud)
这是我目前的代码:
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;
Run Code Online (Sandbox Code Playgroud)
但如上所述,我试图找出建模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;}
}
Run Code Online (Sandbox Code Playgroud)
在上面这个例子中,Tickets集合中会有三个条目.
此外,上面的JSON格式是正常的,因为我从来没有看到这分为模式和数据部分(我可以看到它可能会节省一些空间但在这种情况下消息不是那么大)
Des*_*tar 20
在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; }
}
Run Code Online (Sandbox Code Playgroud)
string json = File.ReadAllText("json.txt");
Rootobject root = new Rootobject();
root.Property1 = JsonConvert.DeserializeObject<Class1[]>(json);
Run Code Online (Sandbox Code Playgroud)
我同意 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; }
}
Run Code Online (Sandbox Code Playgroud)
我能够让你的字符串(未改变)使用JSON.Net进行反序列化,如下所示:
var jsonDto = JsonConvert.DeserializeObject<JsonDto[]>(json);
Run Code Online (Sandbox Code Playgroud)
如果您仍然遇到问题,请告诉我。