【问题标题】:Parse JSON file in ASP.NET MVC and display the data在 ASP.NET MVC 中解析 JSON 文件并显示数据
【发布时间】:2017-08-26 23:48:56
【问题描述】:

帮我找出错误,为什么它不起作用? 我以这个 (https://www.newtonsoft.com/json/help/html/DeserializeWithLinq.htm) 文档为指导。

这是我的控制器:

    public class HomeController : Controller
    {
        [HttpGet]
        public ActionResult Index()
        {
            // Example JSON
            var webClient = new WebClient();
            var json = webClient.DownloadString(@"http://www.json-generator.com/api/json/get/ckJzNVJRIO?indent=2");
            JArray flypoolArray = JArray.Parse(json);
            IList<flypool> blogPosts = flypoolArray.Select(p => new flypool
            {
                hashRate = (string)p["data"]["hashRate"],
                blocksPerHour = (string)p["data"]["blocksPerHour"],
                priceUsd = (string)p["data"]["priceUsd"],
                priceBtc = (string)p["data"]["priceBtc"],
            }).ToList();

            return View(blogPosts);
        }
    }

类 flypool.cs

namespace WebApplicationParse.Models
{
    public class flypool
    {
        public string hashRate { get; set; }
        public string blocksPerHour { get; set; }
        public string priceUsd { get; set; }
        public string priceBtc { get; set; }
    }
}

查看Index.cshtml

@model WebApplicationParse.Models.flypool

@{
    ViewBag.Title = "Index";
}

<h2>Index</h2>

<div class="container">
    <div class="col-md-6 col-md-offset-3">
        <ul>
            <li>@Model.hashRate</li>
        </ul>
    </div>
</div>

在此处显示此错误"Error reading JArray from JsonReader. Current JsonReader item is not an array: StartObject. Path '', line 1, position 1."
请帮帮我。

【问题讨论】:

  • 查看 JSON。它不是一个数组。仔细查看文档中的 JSON。它一个数组。
  • 帮忙修复,不知道要改什么,还是报错。
  • 好吧,让我们考虑一下。您正在使用 JArray 解析 JSON object。也许您需要使用的是JObject

标签: c# json asp.net-mvc parsing


【解决方案1】:

查看 JSON 字符串它不是一个数组,它是 JSON 对象,其中包含几个数组,查看你的类,你想要来自数据对象的 4 个属性,这不是数组,意味着你只有这些属性的一个值。

更好的方法是创建您自己的类并执行this 之类的操作,但适用于所有属性。我认为您正在尝试这种方式,但是您应该包括所有属性,状态,数据,并且数据应该是另一个包含所有属性的类,请参阅图像中收到的数据@

另一种方法将其反序列化为动态对象并相应地分配值,就像这样

var json = webClient.DownloadString(@"http://www.json-generator.com/api/json/get/ckJzNVJRIO?indent=2");
dynamic TheJsonObj = JObject.Parse(json);
flypool  theData = new flypool{
    hashRate = TheJsonObj.data.hasRate,
        blocksPerHour = TheJsonObj.data.blocksPerHour,
        priceUsd  = TheJsonObj.data.priceUsd  ,
        priceBtc= TheJsonObj.data.priceBtc
};

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-10-03
    • 1970-01-01
    • 2021-05-02
    • 2022-01-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多