如何在不预定义 JSON 结构的情况下将 JSON 响应显示到 MVC 视图中?

我对 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>

希望有人可以帮助我。


慕雪6442864
浏览 63回答 1
1回答

慕妹3146593

您可以使用JObject来自 Json.Net 的 a 来读取 json 对象而无需定义类。一个例子:{&nbsp; "key1": "value1",&nbsp; "key2": {&nbsp; &nbsp; "subkey1": 123&nbsp; },&nbsp; "key3": [&nbsp; &nbsp; 3.1415926535,&nbsp; &nbsp; 3.621,&nbsp; &nbsp; 13.37&nbsp; ]}@{string content = ...; // String containing the json data.var json = JObject.Parse(content);}div class="row"><div class="col-md-4">&nbsp; &nbsp; <h2>Getting started</h2>&nbsp; &nbsp; <p>key1: </p>&nbsp; &nbsp; <p>@json["key1"].Value<string>()</p><br>&nbsp; &nbsp; <!-- Returns "value1" -->&nbsp; &nbsp; <p>key2.subkey1: </p>&nbsp; &nbsp; <p>@json["key2"]["subkey1"].Value<int>()</p><br>&nbsp; &nbsp; <!-- Returns 123 -->&nbsp; &nbsp; <p>key3: </p>&nbsp; &nbsp; @foreach(var value in json["key3"].Values<double>())&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; <p>@value</p>&nbsp; &nbsp; }&nbsp; &nbsp; <!-- Returns -->&nbsp; &nbsp; <!-- 3.1415926535 -->&nbsp; &nbsp; <!-- 3.621 -->&nbsp; &nbsp; <!-- 13.37 --></div><div class="col-md-4"></div><div class="col-md-4"></div>
打开App,查看更多内容
随时随地看视频慕课网APP