简体   繁体   English

将JSON值分配给C#中的属性

[英]Assign JSON value to property in C#

From an API I receive a JSON-object that looks like this: 从API中,我收到一个看起来像这样的JSON对象:

{
  "wind" : {
    "speed" : 7.31,
    "deg" : 187.002
  },
  "rain" : {
    "3h" : 0
  },
  "clouds" : {
    "all" : 92
  },
  "coord" : {
    "lon" : 139,
    "lat" : 35
  },
  "dt" : 1369824698,
  "id" : 1851632,
  "cod" : 200,
  "weather" : [
    {
      "id" : 804,
      "main" : "clouds",
      "icon" : "04n",
      "description" : "overcast clouds"
    }
  ],
  "main" : {
    "humidity" : 89,
    "temp_max" : 292.04,
    "temp_min" : 287.04,
    "temp" : 289.5,
    "pressure" : 1013
  },
  "sys" : {
    "country" : "JP",
    "sunrise" : 1369769524,
    "sunset" : 1369821049
  },
  "name" : "Shuzenji"
}

I would like to assign two of these values to my class: 我想为我的班级分配以下两个值:

public class Weather {
  public string Name { get; set; }
  public string Temp { get; set; }
}

The name I can assign like this: 我可以这样分配名称:

weather.Name = TheJSON.name.ToString();

But the temp is trickier, because it's nested inside the "main"-array. 但是温度是比较棘手的,因为它嵌套在“主”数组中。 I´ve seen many examples on how to do this in Javascript but not so much in C#. 我已经看到了很多有关如何在Javascript中执行此操作的示例,但在C#中却很少。 Thanks! 谢谢!

The easiest way to work with JSON data is to deserialize them as C# objects and directly use them in your application. 使用JSON数据的最简单方法是将它们反序列化为C#对象,然后在应用程序中直接使用它们。 You can use a tool like JSON C# Class Generator to automatically generate the C# class from the JSON data. 您可以使用JSON C#类生成器之类的工具从JSON数据自动生成C#类。 Once you have your C# classes generated, you can deserialize the JSON string using the JsonConvert.DeserializeObject(jsonText); 生成C#类后,可以使用JsonConvert.DeserializeObject(jsonText);反序列化JSON字符串。 The generated code requires Newtonsoft Json.NET which you can easily add as a NuGet package . 生成的代码需要Newtonsoft Json.NET ,您可以轻松地将其添加为NuGet包

If you save your JSON content in D:\\test.json, you can use the following code to access the values using the C# objects generated. 如果将JSON内容保存在D:\\ test.json中,则可以使用以下代码使用生成的C#对象访问值。 The example below is to just give you an idea on the usage. 下面的示例只是给您一个用法的想法。

var json = File.ReadAllText(@"D:\test.json");
var weather = JsonConvert.DeserializeObject<Weather>(json);
Console.WriteLine(weather.Name);
Console.WriteLine(weather.Sys.Country);

Main is not an array. Main不是数组。 It is an object, so 这是一个对象,所以

TheJSON.main.temp.ToString()

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

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