简体   繁体   English

C#和天气API,获取特定数据

[英]C# and weather API, fetch specific data

I am getting data from weather API and I would like to return only specific data lets say humidity not the whole object. 我正在从天气API中获取数据,我只想返回特定的数据,例如湿度而不是整个对象。

public Object getWeatherForcast()
    {
        string url = "http://api.openweathermap.org/data/2.5/weather?q=Aalborg&APPID=appid&units=imerial";

        var client = new WebClient();
        var content = client.DownloadString(url);
        var serializer = new JavaScriptSerializer();
        var jsonContent = serializer.Deserialize<Object>(content);

        //here if I use only jsonContent it returns all data, unfortunately I don t know how to get
        //the specific data
        return jsonContent.main.humidity;


    }

here if I use only jsonContent it returns all data, unfortunately I don t know how to get the specific data 在这里,如果我只使用jsonContent,它将返回所有数据,不幸的是我不知道如何获取特定数据

在此处输入图片说明

在此处输入图片说明

Instead of deserializing to a type Object , it would be recommended that you deserialize to your own type of object, like Weather report or something like that, so you can do something like this: 建议您不要反序列化为自己的Object类型,而不是反序列化为Object类型,例如Weather report或类似的东西,因此可以执行以下操作:

WeatherReport report = serializer.Deserialize<WeatherReport>(content);

That would be much easy for you. 这对您来说很容易。

Anyway, given what you have right there, you can do something like this: 无论如何,鉴于您在那里所拥有的,您可以执行以下操作:

jsonContent.main[2].ToString(); //Or whatever other method or property you prefer

It would be better to prepare a class(es) representing the data you want to read from the JSON, as already mentioned, but if you want to keep it your way, or just read single value (eg humidity from "main" section), you may use dynamic with the following small code snippet: 如前所述,最好准备一个表示要从JSON读取的数据的类,但是如果您希望按照自己的方式进行操作,或者只读取单个值(例如,“主要”部分的湿度) ,您可以将dynamic与以下小代码段一起使用:

var jsonContent = serializer.Deserialize<dynamic>(content);
var humidity = jsonContent["main"]["humidity"];

EDIT 编辑

In your case JavaScriptSerializer deserializes objects to Dictionary<string, object> , so you have to access it's properties with indexer, as showed above. 对于您的情况, JavaScriptSerializer将对象反序列化为Dictionary<string, object> ,因此您必须使用索引器访问其属性,如上所示。 If you use Newtonsoft.Json library to deserialize JSON, using dynamic as well, you could get something like the following, cleaner sample, accessing the data using properties: 如果您还使用Newtonsoft.Json库通过dynamic方法反序列化JSON,则可以获得类似以下更干净的示例,并使用属性访问数据:

var jsonContent = JsonConvert.DeserializeObject<dynamic>(content);
humidity = jsonContent.main.humidity;

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM