MVC 5使用Json

时间:2015-07-05 01:51:22

标签: json asp.net-mvc

我有以下ActionResult:

public ActionResult WeatherWidget()
{
    string json = string.Empty;
    using (var client = new WebClient())
    {
        json = client.DownloadString("http://api.wunderground.com/api/xxxxxxxxx/geolookup/conditions/forecast/q/Australia/sydney.json");
    }

    WeatherWidget weatherWidget = new WeatherWidget()
    {
        //What do I put in here?
    };

    return View(weatherWidget);
}

以下型号:

public class WeatherWidget
{
    public string city { get; set; }
    public string lat { get; set; }
    public string lon { get; set; }
}

以下是json的片段:

{
  "response": {
  "version":"0.1",
  "termsofService":"http://www.wunderground.com/weather/api/d/terms.html",
  "features": {
  "geolookup": 1
  ,
  "conditions": 1
  ,
  "forecast": 1
  }
    }
    ,"location": {
        "type":"INTLCITY",
        "country":"AU",
        "country_iso3166":"AU",
        "country_name":"Australia",
        "state":"VC",
        "city":"Falls Creek",
        "tz_short":"AEST",
        "tz_long":"Australia/Melbourne",
        "lat":"-36.86999893",
        "lon":"147.27000427",
        "zip":"00000",

如何填充模型以在我的视图中显示?

例如.. @ Model.city @ Html.Raw(Model.city)

我在我的视图中通过Javascript显示数据没有问题,我可以使用HtmlAgilityPack使用XML和Html执行此操作,我只是无法解决如何使用Json进行操作。

1 个答案:

答案 0 :(得分:1)

通过NuGet添加Newtonsoft.Json,添加以下using语句

using Newtonsoft.Json;
using Newtonsoft.Json.Linq;

然后使用以下代码从JSON响应中提取数据。

  JObject parsedJson = (JObject)JsonConvert.DeserializeObject(json);
  JObject location = (JObject)parsedJson["location"];
  WeatherWidget weatherWidget = new WeatherWidget();
  weatherWidget.city = location["city"];
  weatherWidget.lat = location["lat"];
  weatherWidget.lon = location["lon"];