1

我成功地从这个简单的 json 中得到了结果,并使用以下代码显示在视图中。

物种控制器.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);
   }
  }
 }

物种.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; }
  }
}

物种详细信息.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>

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

    {"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"
    }]
  }
4

2 回答 2

1

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

于 2018-06-20T06:45:23.063 回答
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;
于 2018-06-20T07:50:37.857 回答