简体   繁体   English

如何使用.NET解析此第三方JSON服务?

[英]How to parse this 3rd party JSON service using .NET?

I am trying to read a web service api via my .NET desktop application. 我正在尝试通过.NET桌面应用程序阅读Web服务api。 I have tried the following, but nothing is being populated. 我已经尝试了以下方法,但是没有任何内容。 Via Fiddler, if I click on the [Raw] tab, the response looks like: 通过Fiddler,如果我单击[Raw]选项卡,则响应如下所示:

HTTP/1.1 200 OK 
Date: Fri, 01 Aug 2014 21:49:48 GMT 
Server: Apache
X-Powered-By: PHP/5.3.3 
Connection: close 
Content-Length: 125478
Access-Control-Allow-Origin: * 
Content-Type: application/json
Content-Language: en

{"request":{"command":"project","project_id":"XYZ123"},"project":[{"project_id":"XYZ123","name":"Project Financials","description":"Sales","state":"CA","dept":"Finance","modified":"2014-08-01","data":[["20140801", 112423],["20140731", 689944],["20140730", 9855], ["20140729", 13118], ["20140728", 9448],
... more data ...
["20140318", 1546], ["20140317", 5467], ["20140316", 19578], ["20140315", 90158]]}]}

I would like to capture the data points, ie the "data" from the above JSON segment. 我想捕获数据点,即上述JSON段中的“数据”。 For this I have a simple class as follows: 为此,我有一个简单的类,如下所示:

public class DailySales
{
    public datetime Date { get; set; }
    public int UnitsSold { get; set; }
}

And here is my web service code: 这是我的网络服务代码:

private void GetSales()
{
      var webClient = new WebClient();
      webClient.OpenReadCompleted += webClient_OpenReadCompleted;
      webClient.OpenReadAsync(new Uri("http://3rdPartySite.com));
}

void webClient_OpenReadCompleted(object sender, OpenReadCompletedEventArgs e)
{
      var json = new DataContractJsonSerializer(typeof(List<DailySales>));
      var data = (List<DailySales>)json.ReadObject(e.Result); // returns null  
}

Any tips on what I am missing would be appreciated. 我所缺少的任何提示将不胜感激。

Well, your json isn't deserializing because your class model doesn't match it at all. 好吧,您的json不会反序列化,因为您的类模型根本不匹配它。

First, create a proper model (this was generated using json2csharp ): 首先,创建一个合适的模型(这是使用json2csharp生成的):

public class Request
{
    public string command { get; set; }
    public string project_id { get; set; }
}

public class Project
{
    public string project_id { get; set; }
    public string name { get; set; }
    public string description { get; set; }
    public string state { get; set; }
    public string dept { get; set; }
    public string modified { get; set; }
    public List<List<object>> data { get; set; }
}

public class RootObject
{
    public Request request { get; set; }
    public List<Project> project { get; set; }
}

Note data is generated as a List<List<object>> as it doesn't recognize a common pattern. 注意data由于无法识别公共模式而作为List<List<object>>生成。 You can change that to a class containing an int and a DateTime object, but you'll have to convert that int in your JSON to a DateTime object manually. 您可以将其更改为包含intDateTime对象的类,但是必须手动将JSON中的int转换为DateTime对象。

On the webrequest side, you can use HttpClient along with the new async-await feature in .NET 4.5, along with Json.NET : 在webrequest端,您可以将HttpClient与.NET 4.5中的新async-await功能以及Json.NET一起使用:

public async Task RequestAndDeserializeJson()
{
    var httpClient = new HttpClient();
    var json = await httpClient.GetAsStringAsync("http://3rdPartySite.com");
    RootObject obj = JsonConvert.Deserialize<RootObject>(json);
}

If you only want to extract the data points, you can use JObject.Parse in the Json.NET api: 如果只想提取data点,则可以在Json.NET api中使用JObject.Parse

var jobject = JObject.Parse(json);

// Extract data points only
var dataPoints = jobject["project"]["data"];

You are trying to deserialize into a model that doesn't match the response json at all! 您正在尝试反序列化为完全与响应json不匹配的模型! You have to create the model to match the response, for starters your model class should be named Request, and Data model should be a member of Request model and the type should be a List of List of the model type that you are trying now with. 您必须创建模型以匹配响应,对于初学者而言,您的模型类应命名为Request,而Data模型应是Request模型的成员,并且类型应是您现在尝试使用的模型类型的List of List。 。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何避免使用第三方网络服务重复代码-不使用动态代码? - How to avoid code repetition using a 3rd party web service - without using dynamic? 如何模拟第三方Web服务LINQ数据提供程序? - How to mock a 3rd party web service LINQ data provider? 如何在Azure云服务上使用第三方DLL - How to use 3rd party DLL on Azure Cloud Service ASP.NET Core Web API - 如何使用 HttpClient 使用 3rd 方 API - ASP.NET Core Web API - How to Consume 3rd party API using HttpClient 如何使用protobuf-net或其他序列化程序序列化第三方类型? - How can I serialize a 3rd party type using protobuf-net or other serializers? 屏幕抓取和控制第三方.NET应用程序 - Screenscraping and controlling a 3rd party .NET application 找不到用于ASP.NET服务使用的动态加载的第三方组件的.config文件 - Cannot find .config file for a dynamically loaded 3rd party assembly used by ASP.NET Service 在WinRT组件中使用第三方库 - Using 3rd party libraries in WinRT component 如何从图像读取/写入原始jpeg MCU块? [.net优先使用] [也许使用了第三方iamge库] - how to read/write a raw jpeg MCU block from an image ? [.net preffered] [maybe using a 3rd party iamge library] 从ASP.Net MVC控制器中的第三方API返回JSON字符串 - Returning JSON string from 3rd party API in ASP.Net MVC controller
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM