亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

如何在不預定義 JSON 結構的情況下將 JSON 響應顯示到 MVC 視圖中?

如何在不預定義 JSON 結構的情況下將 JSON 響應顯示到 MVC 視圖中?

C#
慕雪6442864 2022-12-24 14:16:33
我對 ASP.NET 和 MVC 很陌生。我已經創建了一個 MVC asp.net 應用程序,我正在尋找一種方法來顯示我在視圖中從任何Web API 接收到的數據,而無需預定義我的 Web API 響應的 JSON 結構。我從 Web API 獲取數據的控制器如下所示:[HttpGet]public async Task<ActionResult> getCall(){    string url = "http://localhost:51080/";    string customerApi = "customer/1";    using (var client = new HttpClient())    {        client.BaseAddress = new Uri(url);        client.DefaultRequestHeaders.Accept.Clear();        client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));        HttpResponseMessage response = await client.GetAsync(customerApi);        if (response.IsSuccessStatusCode)        {            string jsondata = await response.Content.ReadAsStringAsync();            return Content(jsondata, "application/json");        }        return Json(1, JsonRequestBehavior.AllowGet);    }}我的看法:@using MVCApp.Controllers;@{ViewBag.Title = "Dashboard";if (Session["userID"] == null){    Response.Redirect("~/Login/Index");}else{     ((HomeController)this.ViewContext.Controller).getCall();}}<div class="row"><div class="col-md-4">    <h2>Getting started</h2>    <p>    <!-- Labels with values here! -->    </p></div><div class="col-md-4"></div><div class="col-md-4"></div>希望有人可以幫助我。
查看完整描述

1 回答

?
慕妹3146593

TA貢獻1820條經驗 獲得超9個贊

您可以使用JObject來自 Json.Net 的 a 來讀取 json 對象而無需定義類。一個例子:


{

  "key1": "value1",

  "key2": {

    "subkey1": 123

  },

  "key3": [

    3.1415926535,

    3.621,

    13.37

  ]

}

@{

string content = ...; // String containing the json data.

var json = JObject.Parse(content);

}

div class="row">

<div class="col-md-4">

    <h2>Getting started</h2>

    <p>key1: </p>

    <p>@json["key1"].Value<string>()</p><br>

    <!-- Returns "value1" -->

    <p>key2.subkey1: </p>

    <p>@json["key2"]["subkey1"].Value<int>()</p><br>

    <!-- Returns 123 -->

    <p>key3: </p>

    @foreach(var value in json["key3"].Values<double>())

    {

      <p>@value</p>

    }

    <!-- Returns -->

    <!-- 3.1415926535 -->

    <!-- 3.621 -->

    <!-- 13.37 -->

</div>

<div class="col-md-4">

</div>

<div class="col-md-4">

</div>


查看完整回答
反對 回復 2022-12-24
  • 1 回答
  • 0 關注
  • 98 瀏覽

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號