如何从ASP.NET MVC

时间:2018-06-20 06:32:17

标签: c# json asp.net-mvc

我成功地从this简单json中获得了结果,并使用以下代码将其显示在视图中。

  

SpeciesController.cs

using diversity.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using LinqToWiki.Download;
using LinqToWiki.Generated;
using LinqToWiki;
using System.Text;
using RestSharp;
using Newtonsoft.Json.Linq;
using System.Net.Http;
using Newtonsoft.Json;

namespace diversity.Controllers
{
 public class SpeciesController : Controller
 {
  public async System.Threading.Tasks.Task<ActionResult> SpeciesDetails(){

    HttpClient client = new HttpClient();
    List<Species> datalist = new List<Species>();

    try
    {
        HttpResponseMessage response = await client.GetAsync("https://jsonplaceholder.typicode.com/posts/1");
        response.EnsureSuccessStatusCode();
        string responseBody = await response.Content.ReadAsStringAsync();

        datalist = JsonConvert.DeserializeObject<List<Species>>(responseBody);
    }
    catch (HttpRequestException e)
    {
        System.Diagnostics.Debug.WriteLine("\nException Caught!");
        System.Diagnostics.Debug.WriteLine("Message :{0} ", e.Message);
    }
    client.Dispose();
    return View(datalist);
   }
  }
 }
  

Species.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace diversity.Models
{
  public class Species
  {
   public int UserId { get; set; }
   public int Id { get; set; }
   public string Title { get; set; }
   public string Body { get; set; }
  }
}
  

SpeciesDetails.cshtml

 @model IEnumerable<diversity.Models.Species>

 @{
   ViewBag.Title = "SpeciesDetails";
  Layout = "~/Views/Shared/_Layout.cshtml";
 }

<h2>SpeciesDetails</h2>

<p>
   @Html.ActionLink("Create New", "Create")
</p>

 <table class="table">
<tr>
<th>
    @Html.DisplayNameFor(model => model.UserId)
</th>
<th>
    @Html.DisplayNameFor(model => model.Title)
</th>
<th>
    @Html.DisplayNameFor(model => model.Body)
</th>
<th></th>
</tr>

@foreach (var item in Model) {
<tr>
<td>
    @Html.DisplayFor(modelItem => item.UserId)
</td>
<td>
    @Html.DisplayFor(modelItem => item.Title)
</td>
<td>
    @Html.DisplayFor(modelItem => item.Body)
</td>
<td>
    @Html.ActionLink("Edit", "Edit", new { id=item.Id }) |
    @Html.ActionLink("Details", "Details", new { id=item.Id }) |
    @Html.ActionLink("Delete", "Delete", new { id=item.Id })
    </td>
    </tr>
   }

  </table>

但是现在我想从this中显示复杂的嵌套json结果。另外,我只想显示一些属性,例如“家庭”,“属”等。我知道here中的问题。 在.NET HTTP Client中执行此操作的正确方法是什么?那我应该如何修改我的模型?

    {"offset":0,
  "limit":20,
  "endOfRecords":false,
  "count":49,
  "results":[{
    "key":104061090,
    "datasetKey":"fab88965-e69d-4491-a04d-e3198b626e52",
    "nubKey":2435098,
    "parentKey":104060851,
    "parent":"Felinae",
    "kingdom":"Metazoa",
    "phylum":"Chordata",
    "order":"Carnivora",
    "family":"Felidae",
    "genus":"Puma",
    "kingdomKey":103832354,
    "phylumKey":103882489,
    "classKey":104045725,
    "orderKey":104059711,
    "familyKey":104060843,
    "genusKey":104061090,
    "scientificName":"Puma",
    "canonicalName":"Puma",
    "authorship":"",
    "nameType":"SCIENTIFIC",
    "taxonomicStatus":"ACCEPTED",
    "rank":"GENUS",
    "origin":"SOURCE",
    "numDescendants":4,
    "numOccurrences":0,
    "habitats":[],
    "nomenclaturalStatus":[],
    "threatStatuses":[],
    "descriptions":[],
    "vernacularNames":[],
    "higherClassificationMap":{
      "103832354":"Metazoa",
      "103882489":"Chordata",
      "104045725":"Mammalia",
      "104059711":"Carnivora",
      "104060843":"Felidae",
      "104060851":"Felinae"
      },
    "synonym":false,
    "class":"Mammalia"
    }]
  }

2 个答案:

答案 0 :(得分:1)

首先,您必须在适当的模型中反序列化JSON,为此,可以使用http://json2csharp.com/,然后如果不需要View中的所有数据。您可以手动或使用“ Automapper”之类的东西在其他模型中对其进行变换,或者根本无法在View中显示所有值。

答案 1 :(得分:1)

使用此作为您的模型类:

 using System.Collections.Generic;

    using Newtonsoft.Json;

    public partial class JsonModel
    {
        [JsonProperty("offset")]
        public long Offset { get; set; }

        [JsonProperty("limit")]
        public long Limit { get; set; }

        [JsonProperty("endOfRecords")]
        public bool EndOfRecords { get; set; }

        [JsonProperty("count")]
        public long Count { get; set; }

        [JsonProperty("results")]
        public List<Result> Results { get; set; }
    }

    public partial class Result
    {
        [JsonProperty("key")]
        public long Key { get; set; }

        [JsonProperty("datasetKey")]
        public string DatasetKey { get; set; }

        [JsonProperty("nubKey")]
        public long NubKey { get; set; }

        [JsonProperty("parentKey")]
        public long ParentKey { get; set; }

        [JsonProperty("parent")]
        public string Parent { get; set; }

        [JsonProperty("kingdom")]
        public string Kingdom { get; set; }

        [JsonProperty("phylum")]
        public string Phylum { get; set; }

        [JsonProperty("order")]
        public string Order { get; set; }

        [JsonProperty("family")]
        public string Family { get; set; }

        [JsonProperty("genus")]
        public string Genus { get; set; }

        [JsonProperty("kingdomKey")]
        public long KingdomKey { get; set; }

        [JsonProperty("phylumKey")]
        public long PhylumKey { get; set; }

        [JsonProperty("classKey")]
        public long ClassKey { get; set; }

        [JsonProperty("orderKey")]
        public long OrderKey { get; set; }

        [JsonProperty("familyKey")]
        public long FamilyKey { get; set; }

        [JsonProperty("genusKey")]
        public long GenusKey { get; set; }

        [JsonProperty("scientificName")]
        public string ScientificName { get; set; }

        [JsonProperty("canonicalName")]
        public string CanonicalName { get; set; }

        [JsonProperty("authorship")]
        public string Authorship { get; set; }

        [JsonProperty("nameType")]
        public string NameType { get; set; }

        [JsonProperty("taxonomicStatus")]
        public string TaxonomicStatus { get; set; }

        [JsonProperty("rank")]
        public string Rank { get; set; }

        [JsonProperty("origin")]
        public string Origin { get; set; }

        [JsonProperty("numDescendants")]
        public long NumDescendants { get; set; }

        [JsonProperty("numOccurrences")]
        public long NumOccurrences { get; set; }

        [JsonProperty("habitats")]
        public List<object> Habitats { get; set; }

        [JsonProperty("nomenclaturalStatus")]
        public List<object> NomenclaturalStatus { get; set; }

        [JsonProperty("threatStatuses")]
        public List<object> ThreatStatuses { get; set; }

        [JsonProperty("descriptions")]
        public List<object> Descriptions { get; set; }

        [JsonProperty("vernacularNames")]
        public List<object> VernacularNames { get; set; }

        [JsonProperty("higherClassificationMap")]
        public Dictionary<string, string> HigherClassificationMap { get; set; }

        [JsonProperty("synonym")]
        public bool Synonym { get; set; }

        [JsonProperty("class")]
        public string Class { get; set; }
    }

然后在您的课堂上完成

     var data = JsonConvert.DeserializeObject<JsonModel>("JsonData");
                var result = data.Results;
//Loop as appropriate, using index 0 for testing
                string AuthorShip = result[0].Authorship;
                string Origin = result[0].Origin;
                string parent = result[0].Parent;