【问题标题】:How to read values from a nested json result in ASP.NET MVC如何从 ASP.NET MVC 中的嵌套 json 结果中读取值
【发布时间】:2018-06-20 15:50:37
【问题描述】:

我成功地从thissimple 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);
   }
  }
 }

物种.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 结果。此外,我只想显示一些属性,例如“family”、“genus”等。我知道here 中的问题。 在 .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"
    }]
  }

【问题讨论】:

    标签: c# json asp.net-mvc


    【解决方案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;
    

    【讨论】:

      【解决方案2】:

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

      【讨论】:

        猜你喜欢
        • 2016-08-19
        • 1970-01-01
        • 2020-11-09
        • 1970-01-01
        • 1970-01-01
        • 2014-05-06
        • 1970-01-01
        • 1970-01-01
        • 2023-03-11
        相关资源
        最近更新 更多