【问题标题】:Problem to display json data in .NET core 2.0在 .NET core 2.0 中显示 json 数据的问题
【发布时间】:2020-04-08 23:57:03
【问题描述】:

在 .net core 2.0 应用程序中反序列化后显示数据时遇到问题。这就是我想要做的: 1-解压缩POST请求发送的文件(完成) 2-创建数据模型(完成) 3-显示数据(不行)

这是我的控制器:

值控制器

using System;
using System.Collections.Generic;
using System.IO;
using System.IO.Compression;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;
using HelloWorld.Models;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Newtonsoft.Json;

// For more information on enabling Web API for empty projects, visit https://go.microsoft.com/fwlink/?LinkID=397860

namespace HelloWorld.Controllers
{
    [Route("")]
    public class ValuesController : Controller
    {

        // POST api/<controller>

        [HttpGet]
        [Route("/Values/Index")]

    public IActionResult Index()
{
        using (StreamReader r = new StreamReader("c:\\temp\\inplay-soccer.json"))
        {
            string json = r.ReadToEnd();
            var objects = JsonConvert.DeserializeObject<Goalserve>(json);
            return View(objects);
        }
}

        [HttpPost]
        [Consumes("application/gzip")]
        public async Task<IActionResult> PostAsync(IFormFile file)
        {

                WebClient Client = new WebClient();
                Client.DownloadFile("http://inplay.goalserve.com/inplay-soccer.gz", "C:\\temp\\inplay-soccer.gz");
                using (var inputFileStream = new FileStream("c:\\temp\\inplay-soccer.gz", FileMode.Open))
                using (var gzipStream = new GZipStream(inputFileStream, CompressionMode.Decompress))
                using (var outputFileStream = new FileStream("c:\\temp\\inplay-soccer.json", FileMode.Create))
                {
                    await gzipStream.CopyToAsync(outputFileStream);
                }
                return Ok();
        }

        // PUT api/<controller>/5
        [HttpPut("{id}")]
        public void Put(int id, [FromBody]string value)
        {
        }

        // DELETE api/<controller>/5
        [HttpDelete("{id}")]
        public void Delete(int id)
        {
        }

        public class Value
        {
            public int Id { get; set; }
        }
    }
}

这是模型:

目标服务器类

using Newtonsoft.Json; using Newtonsoft.Json.Converters; using System; using System.Collections.Generic; using System.Globalization; using System.Linq; using System.Threading.Tasks;

namespace HelloWorld.Models {
    public partial class Goalserve
    {
        [JsonProperty("updated")]
        public string Updated { get; set; }

        [JsonProperty("updated_ts")]
        public long UpdatedTs { get; set; }

        [JsonProperty("events")]
        public Events Events { get; set; }
    }

    public partial class Events
    {
        [JsonProperty("84586848")]
        public The84586848 The84586848 { get; set; }
    }

    public partial class The84586848
    {
        [JsonProperty("core")]
        public Core Core { get; set; }

        [JsonProperty("info")]
        public InfoClass Info { get; set; }

        [JsonProperty("stats")]
        public Dictionary<string, Stat> Stats { get; set; }

        [JsonProperty("odds")]
        public Dictionary<string, Odd> Odds { get; set; }
    }

    public partial class Core
    {
        [JsonProperty("safe")]
        public long Safe { get; set; }

        [JsonProperty("stopped")]
        public long Stopped { get; set; }

        [JsonProperty("blocked")]
        public long Blocked { get; set; }

        [JsonProperty("finished")]
        public long Finished { get; set; }

        [JsonProperty("updated")]
        public DateTimeOffset Updated { get; set; }

        [JsonProperty("updated_ts")]
        public long UpdatedTs { get; set; }
    }

    public partial class InfoClass
    {
        [JsonProperty("id")]
        public long Id { get; set; }

        [JsonProperty("name")]
        public string Name { get; set; }

        [JsonProperty("sport")]
        public string Sport { get; set; }

        [JsonProperty("league")]
        public string League { get; set; }

        [JsonProperty("start_time")]
        public string StartTime { get; set; }

        [JsonProperty("start_date")]
        public string StartDate { get; set; }

        [JsonProperty("start_ts")]
        public long StartTs { get; set; }

        [JsonProperty("period")]
        public string Period { get; set; }

        [JsonProperty("minute")]
        [JsonConverter(typeof(ParseStringConverter))]
        public long Minute { get; set; }

        [JsonProperty("secunds")]
        public string Secunds { get; set; }

        [JsonProperty("score")]
        public string Score { get; set; }

        [JsonProperty("points")]
        public string Points { get; set; }

        [JsonProperty("pitch")]
        public string Pitch { get; set; }

        [JsonProperty("ball_pos")]
        public string BallPos { get; set; }

        [JsonProperty("add_time")]
        public string AddTime { get; set; }

        [JsonProperty("player")]
        public string Player { get; set; }

        [JsonProperty("state")]
        [JsonConverter(typeof(ParseStringConverter))]
        public long State { get; set; }
    }

    public partial class Odd
    {
        [JsonProperty("id")]
        public long Id { get; set; }

        [JsonProperty("name")]
        public string Name { get; set; }

        [JsonProperty("short_name")]
        public string ShortName { get; set; }

        [JsonProperty("suspend")]
        public long Suspend { get; set; }

        [JsonProperty("order")]
        public long Order { get; set; }

        [JsonProperty("info")]
        public InfoEnum Info { get; set; }

        [JsonProperty("participants")]
        public Dictionary<string, Participant> Participants { get; set; }
    }

    public partial class Participant
    {
        [JsonProperty("id")]
        public long Id { get; set; }

        [JsonProperty("order")]
        public long Order { get; set; }

        [JsonProperty("name")]
        public string Name { get; set; }

        [JsonProperty("short_name")]
        public string ShortName { get; set; }

        [JsonProperty("value_eu")]
        public string ValueEu { get; set; }

        [JsonProperty("value_na")]
        public string ValueNa { get; set; }

        [JsonProperty("value_us")]
        public string ValueUs { get; set; }

        [JsonProperty("handicap")]
        public string Handicap { get; set; }

        [JsonProperty("suspend")]
        public long Suspend { get; set; }
    }

    public partial class Stat
    {
        [JsonProperty("name")]
        public string Name { get; set; }

        [JsonProperty("home")]
        public string Home { get; set; }

        [JsonProperty("away")]
        public string Away { get; set; }
    }

    public enum InfoEnum { Count070007959, CurrentCorners11, Empty };

    internal static class Converter
    {
        public static readonly JsonSerializerSettings Settings = new JsonSerializerSettings
        {
            MetadataPropertyHandling = MetadataPropertyHandling.Ignore,
            DateParseHandling = DateParseHandling.None,
            Converters =
            {
                InfoEnumConverter.Singleton,
                new IsoDateTimeConverter { DateTimeStyles = DateTimeStyles.AssumeUniversal }
            },
        };
    }

    internal class ParseStringConverter : JsonConverter
    {
        public override bool CanConvert(Type t) => t == typeof(long) || t == typeof(long?);

        public override object ReadJson(JsonReader reader, Type t, object existingValue, JsonSerializer serializer)
        {
            if (reader.TokenType == JsonToken.Null) return null;
            var value = serializer.Deserialize<string>(reader);
            long l;
            if (Int64.TryParse(value, out l))
            {
                return l;
            }
            throw new Exception("Cannot unmarshal type long");
        }

        public override void WriteJson(JsonWriter writer, object untypedValue, JsonSerializer serializer)
        {
            if (untypedValue == null)
            {
                serializer.Serialize(writer, null);
                return;
            }
            var value = (long)untypedValue;
            serializer.Serialize(writer, value.ToString());
            return;
        }

        public static readonly ParseStringConverter Singleton = new ParseStringConverter();
    }

    internal class InfoEnumConverter : JsonConverter
    {
        public override bool CanConvert(Type t) => t == typeof(InfoEnum) || t == typeof(InfoEnum?);

        public override object ReadJson(JsonReader reader, Type t, object existingValue, JsonSerializer serializer)
        {
            if (reader.TokenType == JsonToken.Null) return null;
            var value = serializer.Deserialize<string>(reader);
            switch (value)
            {
                case "":
                    return InfoEnum.Empty;
                case "Count : 0 (70:00 - 79:59)":
                    return InfoEnum.Count070007959;
                case "Current Corners : 11":
                    return InfoEnum.CurrentCorners11;
            }
            throw new Exception("Cannot unmarshal type InfoEnum");
        }

        public override void WriteJson(JsonWriter writer, object untypedValue, JsonSerializer serializer)
        {
            if (untypedValue == null)
            {
                serializer.Serialize(writer, null);
                return;
            }
            var value = (InfoEnum)untypedValue;
            switch (value)
            {
                case InfoEnum.Empty:
                    serializer.Serialize(writer, "");
                    return;
                case InfoEnum.Count070007959:
                    serializer.Serialize(writer, "Count : 0 (70:00 - 79:59)");
                    return;
                case InfoEnum.CurrentCorners11:
                    serializer.Serialize(writer, "Current Corners : 11");
                    return;
            }
            throw new Exception("Cannot marshal type InfoEnum");
        }

        public static readonly InfoEnumConverter Singleton = new InfoEnumConverter();
    } }

现在,如何在视图中显示数据?

我创建了一个名为“Index.cshtml”的相应视图并尝试使用 ViewData,但我不知道该怎么做。这是我的查看代码

Index.cshtml

@page
@model HelloWorld.Models.Goalserve
@{
    var objects = ViewData["Objects"];
}
<table>
    <tr>
        test
        <td>@objects.ToString()</td>
    </tr>
</table>

我知道查看代码“索引”是错误的。我应该怎么做才能显示反序列化的 JSON 提要(例如,一行中的每个信息)? (我需要在[Route("/Values/Index")]中显示数据)

谢谢!

EDIT : ERROR -> AspNetCore.Views_Values_Index+<ExecuteAsync>d__0.MoveNext()
System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
Microsoft.AspNetCore.Mvc.Razor.RazorView+<RenderPageCoreAsync>d__20.MoveNext()
System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
Microsoft.AspNetCore.Mvc.Razor.RazorView+<RenderPageAsync>d__19.MoveNext()
System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
Microsoft.AspNetCore.Mvc.Razor.RazorView+<RenderAsync>d__18.MoveNext()
System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
Microsoft.AspNetCore.Mvc.ViewFeatures.ViewExecutor+<ExecuteAsync>d__22.MoveNext()
System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
Microsoft.AspNetCore.Mvc.ViewFeatures.ViewExecutor+<ExecuteAsync>d__21.MoveNext()
System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
Microsoft.AspNetCore.Mvc.ViewFeatures.ViewResultExecutor+<ExecuteAsync>d__6.MoveNext()
System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
Microsoft.AspNetCore.Mvc.ViewResult+<ExecuteResultAsync>d__26.MoveNext()
System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
Microsoft.AspNetCore.Mvc.Internal.ResourceInvoker+<InvokeResultAsync>d__20.MoveNext()
System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
Microsoft.AspNetCore.Mvc.Internal.ResourceInvoker+<InvokeNextResultFilterAsync>d__28.MoveNext()
System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
Microsoft.AspNetCore.Mvc.Internal.ResourceInvoker.Rethrow(ResultExecutedContext context)
Microsoft.AspNetCore.Mvc.Internal.ResourceInvoker.ResultNext<TFilter, TFilterAsync>(ref State next, ref Scope scope, ref object state, ref bool isCompleted)
Microsoft.AspNetCore.Mvc.Internal.ResourceInvoker+<InvokeResultFilters>d__26.MoveNext()
System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
Microsoft.AspNetCore.Mvc.Internal.ResourceInvoker+<InvokeNextResourceFilter>d__23.MoveNext()
System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
Microsoft.AspNetCore.Mvc.Internal.ResourceInvoker.Rethrow(ResourceExecutedContext context)
Microsoft.AspNetCore.Mvc.Internal.ResourceInvoker.Next(ref State next, ref Scope scope, ref object state, ref bool isCompleted)
Microsoft.AspNetCore.Mvc.Internal.ResourceInvoker+<InvokeFilterPipelineAsync>d__18.MoveNext()
System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
Microsoft.AspNetCore.Mvc.Internal.ResourceInvoker+<InvokeAsync>d__16.MoveNext()
System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
Microsoft.AspNetCore.Builder.RouterMiddleware+<Invoke>d__4.MoveNext()
System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
Microsoft.AspNetCore.Diagnostics.DeveloperExceptionPageMiddleware+<Invoke>d__7.MoveNext()

Show raw exception details
System.NullReferenceException: Object reference not set to an instance of an object.
   at AspNetCore.Views_Values_Index.<ExecuteAsync>d__0.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at Microsoft.AspNetCore.Mvc.Razor.RazorView.<RenderPageCoreAsync>d__20.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at Microsoft.AspNetCore.Mvc.Razor.RazorView.<RenderPageAsync>d__19.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at Microsoft.AspNetCore.Mvc.Razor.RazorView.<RenderAsync>d__18.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at Microsoft.AspNetCore.Mvc.ViewFeatures.ViewExecutor.<ExecuteAsync>d__22.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at Microsoft.AspNetCore.Mvc.ViewFeatures.ViewExecutor.<ExecuteAsync>d__21.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at Microsoft.AspNetCore.Mvc.ViewFeatures.ViewResultExecutor.<ExecuteAsync>d__6.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at Microsoft.AspNetCore.Mvc.ViewResult.<ExecuteResultAsync>d__26.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at Microsoft.AspNetCore.Mvc.Internal.ResourceInvoker.<InvokeResultAsync>d__20.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at Microsoft.AspNetCore.Mvc.Internal.ResourceInvoker.<InvokeNextResultFilterAsync>d__28`2.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
   at Microsoft.AspNetCore.Mvc.Internal.ResourceInvoker.Rethrow(ResultExecutedContext context)
   at Microsoft.AspNetCore.Mvc.Internal.ResourceInvoker.ResultNext[TFilter,TFilterAsync](State& next, Scope& scope, Object& state, Boolean& isCompleted)
   at Microsoft.AspNetCore.Mvc.Internal.ResourceInvoker.<InvokeResultFilters>d__26.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at Microsoft.AspNetCore.Mvc.Internal.ResourceInvoker.<InvokeNextResourceFilter>d__23.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
   at Microsoft.AspNetCore.Mvc.Internal.ResourceInvoker.Rethrow(ResourceExecutedContext context)
   at Microsoft.AspNetCore.Mvc.Internal.ResourceInvoker.Next(State& next, Scope& scope, Object& state, Boolean& isCompleted)
   at Microsoft.AspNetCore.Mvc.Internal.ResourceInvoker.<InvokeFilterPipelineAsync>d__18.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at Microsoft.AspNetCore.Mvc.Internal.ResourceInvoker.<InvokeAsync>d__16.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at Microsoft.AspNetCore.Builder.RouterMiddleware.<Invoke>d__4.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at Microsoft.AspNetCore.Diagnostics.DeveloperExceptionPageMiddleware.<Invoke>d__7.MoveNext()

【问题讨论】:

  • 你能发布你的Goalsserve类定义吗?谢谢。
  • 抱歉打错了。 Feed 类实际上是goalserve 类。
  • 我做了一个编辑。泰。
  • 如果要显示 JSON,为什么要反序列化呢?
  • 我想显示反序列化的数据而不是json数据。主题中又犯了一个错误,抱歉。

标签: asp.net .net json asp.net-core .net-core


【解决方案1】:

请修改您的 index.cshtml 如下:

@model HelloWorld.Models.Goalserve
@{
    var objects = Model; //ViewData["Objects"];
}
<table>
    <tr>
        test
        <td>@objects.ToString()</td>
    </tr>

请修改您的目标服务和事件如下:

public partial class Goalserve
{
    [JsonProperty("updated")]
    public string Updated { get; set; }

    [JsonProperty("updated_ts")]
    public long UpdatedTs { get; set; }

    [JsonProperty("events")]
    //public Events Events { get; set; }
    public Dictionary<string, Events> Events { get; set; }

    public override string ToString()
    {
        return string.Format($"Updated={this.Updated} and UpdatedTs={this.UpdatedTs} and EventsCount={this.Events.Count}");
    }
}

public partial class Events
{
    //[JsonProperty("84586848")]
    public The84586848 The84586848 { get; set; }
}

请修改您的转换器以包括 ParseStringConverter:

internal static class Converter
{
    public static readonly JsonSerializerSettings Settings = new JsonSerializerSettings
    {
        MetadataPropertyHandling = MetadataPropertyHandling.Ignore,
        DateParseHandling = DateParseHandling.None,
        Converters =
        {
            InfoEnumConverter.Singleton,
            ParseStringConverter.Singleton,
            new IsoDateTimeConverter { DateTimeStyles = DateTimeStyles.AssumeUniversal }
        },
    };
}

然后最后修改您的控制器操作以使用您的自定义设置,如下所示:

using (StreamReader r = new StreamReader("c:\\temp\\inplay-soccer.json"))
{
    string json = r.ReadToEnd();
    objects = JsonConvert.DeserializeObject<Goalserve>(json, Converter.Settings);
    return View(objects);
}

上面的代码可以与您附加的示例 json(文本文件)一起正常工作。您附加的 json 在与键 84586848 匹配的事件集合下没有对象。

侧面但相关的说明:如果你想让NewtonSoft Json使用camelCase,那么你可以使用ContractResolver = new CamelCasePropertyNamesContractResolver()而不是在属性中添加[JsonProperty]注解。例如,

internal static class Converter
{
    public static readonly JsonSerializerSettings Settings = new JsonSerializerSettings
    {
        MetadataPropertyHandling = MetadataPropertyHandling.Ignore,
        DateParseHandling = DateParseHandling.None,
        ContractResolver = new CamelCasePropertyNamesContractResolver(),
        Converters =
        {
            InfoEnumConverter.Singleton,
            ParseStringConverter.Singleton,
            new IsoDateTimeConverter { DateTimeStyles = DateTimeStyles.AssumeUniversal }
        },
    };
}

【讨论】:

  • 没有示例 json,我们在这里帮不上什么忙。
  • 无法打开链接。它说“出了点问题”,页面被重定向到主页
  • 是的,请在反序列化时包含您的自定义转换设置 (Converter.Settings)。我用同样的方式更新了我的帖子。
  • 谢谢山姆。这是我这边的另一个错误......我的“index.cshtml ......一个 Razor 页面进入 .NET Core 应用程序......从逻辑上讲它会失败。
【解决方案2】:

给你的json文件:

  • 您有一个名为 84586848 的模型属性,带有 JsonProperty,但您的 json 不包含此类属性。
  • InfoEnumConverter中有switch-case语句。它有三种可能,如果是其他类型会抛出异常。需要设置默认返回值而不是抛出异常。(注意:您需要将[JsonConverter(typeof(InfoEnumConverter))] 添加到您的InfoEnum Info 属性中 )

为了适应你的 json 文件,你需要改变模型如下:

public partial class Goalserve
{
    [JsonProperty("updated")]
    public string Updated { get; set; }
    [JsonProperty("updated_ts")]
    public long UpdatedTs { get; set; }
    [JsonProperty("events")]
    public Dictionary<string, The84586848> Events { get; set; }
}

//public partial class Events
//{
//    [JsonProperty("84586848")]
//    public The84586848 The84586848 { get; set; }
//}

public partial class The84586848
{
    [JsonProperty("core")]
    public Core Core { get; set; }
    [JsonProperty("info")]
    public InfoClass Info { get; set; }
    [JsonProperty("stats")]
    public Dictionary<string, Stat> Stats { get; set; }
    [JsonProperty("odds")]
    public Dictionary<string, Odd> Odds { get; set; }
}

public partial class Core
{
    [JsonProperty("safe")]
    public long Safe { get; set; }
    [JsonProperty("stopped")]
    public long Stopped { get; set; }
    [JsonProperty("blocked")]
    public long Blocked { get; set; }
    [JsonProperty("finished")]
    public long Finished { get; set; }
    [JsonProperty("updated")]
    public DateTimeOffset Updated { get; set; }
    [JsonProperty("updated_ts")]
    public long UpdatedTs { get; set; }
}
public partial class InfoClass
{
    [JsonProperty("id")]
    public long Id { get; set; }
    [JsonProperty("name")]
    public string Name { get; set; }
    [JsonProperty("sport")]
    public string Sport { get; set; }
    [JsonProperty("league")]
    public string League { get; set; }
    [JsonProperty("start_time")]
    public string StartTime { get; set; }
    [JsonProperty("start_date")]
    public string StartDate { get; set; }
    [JsonProperty("start_ts")]
    public long StartTs { get; set; }
    [JsonProperty("period")]
    public string Period { get; set; }

    [JsonConverter(typeof(ParseStringConverter))]
    [JsonProperty("minute")]
    public long Minute { get; set; }

    [JsonProperty("secunds")]
    public string Secunds { get; set; }
    [JsonProperty("score")]
    public string Score { get; set; }
    [JsonProperty("points")]
    public string Points { get; set; }
    [JsonProperty("pitch")]
    public string Pitch { get; set; }
    [JsonProperty("ball_pos")]
    public string BallPos { get; set; }
    [JsonProperty("add_time")]
    public string AddTime { get; set; }
    [JsonProperty("player")]
    public string Player { get; set; }

    [JsonConverter(typeof(ParseStringConverter))]
    [JsonProperty("state")]
    public long State { get; set; }
}

public partial class Odd
{
    [JsonProperty("id")]
    public long Id { get; set; }
    [JsonProperty("name")]
    public string Name { get; set; }
    [JsonProperty("short_name")]
    public string ShortName { get; set; }
    [JsonProperty("suspend")]
    public long Suspend { get; set; }
    [JsonProperty("order")]
    public long Order { get; set; }

    [JsonProperty("info")]
    [JsonConverter(typeof(InfoEnumConverter))]
    public InfoEnum Info { get; set; }

    [JsonProperty("participants")]
    public Dictionary<string, Participant> Participants { get; set; }
}

public partial class Participant
{
    [JsonProperty("id")]
    public long Id { get; set; }

    [JsonProperty("order")]
    public long Order { get; set; }

    [JsonProperty("name")]
    public string Name { get; set; }

    [JsonProperty("short_name")]
    public string ShortName { get; set; }

    [JsonProperty("value_eu")]
    public string ValueEu { get; set; }

    [JsonProperty("value_na")]
    public string ValueNa { get; set; }

    [JsonProperty("value_us")]
    public string ValueUs { get; set; }

    [JsonProperty("handicap")]
    public string Handicap { get; set; }

    [JsonProperty("suspend")]
    public long Suspend { get; set; }
}

public partial class Stat
{
    [JsonProperty("name")]
    public string Name { get; set; }

    [JsonProperty("home")]
    public string Home { get; set; }

    [JsonProperty("away")]
    public string Away { get; set; }
}

public enum InfoEnum { Count070007959, CurrentCorners11, Empty,OtherType };

public class ParseStringConverter : JsonConverter
{
    public override bool CanConvert(Type t) => t == typeof(long) || t == typeof(long?);

    public override object ReadJson(JsonReader reader, Type t, object existingValue, JsonSerializer serializer)
    {
        if (reader.TokenType == JsonToken.Null) return null;
        var value = serializer.Deserialize<string>(reader);
        long l;
        if (Int64.TryParse(value, out l))
        {
            return l;
        }
        throw new Exception("Cannot unmarshal type long");
    }

    public override void WriteJson(JsonWriter writer, object untypedValue, JsonSerializer serializer)
    {
        if (untypedValue == null)
        {
            serializer.Serialize(writer, null);
            return;
        }
        var value = (long)untypedValue;
        serializer.Serialize(writer, value.ToString());
        return;
    }

    public static readonly ParseStringConverter Singleton = new ParseStringConverter();
}

public class InfoEnumConverter : JsonConverter
{
    public override bool CanConvert(Type t) => t == typeof(InfoEnum) || t == typeof(InfoEnum?);

    public override object ReadJson(JsonReader reader, Type t, object existingValue, JsonSerializer serializer)
    {
        if (reader.TokenType == JsonToken.Null) return null;
        var value = serializer.Deserialize<string>(reader);
        switch (value)
        {
            case "":
                return InfoEnum.Empty;
            case "Count : 0 (70:00 - 79:59)":
                return InfoEnum.Count070007959;
            case "Current Corners : 10":
                return InfoEnum.CurrentCorners11;
            default:
                return InfoEnum.OtherType;
        }
        //throw new Exception("Cannot unmarshal type InfoEnum");
    }

    public override void WriteJson(JsonWriter writer, object untypedValue, JsonSerializer serializer)
    {
        if (untypedValue == null)
        {
            serializer.Serialize(writer, null);
            return;
        }
        var value = (InfoEnum)untypedValue;
        switch (value)
        {
            case InfoEnum.Empty:
                serializer.Serialize(writer, "");
                return;
            case InfoEnum.Count070007959:
                serializer.Serialize(writer, "Count : 0 (70:00 - 79:59)");
                return;
            case InfoEnum.CurrentCorners11:
                serializer.Serialize(writer, "Current Corners : 11");
                return;
        }
        throw new Exception("Cannot marshal type InfoEnum");
    }

    public static readonly InfoEnumConverter Singleton = new InfoEnumConverter();
}

为了您的观点:

你没有将数据存储到ViewData["objects"],所以你犯了错误,你可以修改如下:

1.控制器:

[HttpGet]
public IActionResult Index()
{
    using (StreamReader r = new StreamReader("c:\\temp\\inplay-soccer.json"))
    {
        string json = r.ReadToEnd();
        var objects = JsonConvert.DeserializeObject<Goalserve>(json);              
        return View(objects);
    }
}

2.查看:

@model Goalserve
@{ 
    var data = Model.Events.Keys.ToArray();
}
<table class="table">

    <tr>
        <td>@Model.Updated</td>
    </tr>
    <tr>
        <td>@Model.UpdatedTs</td>
    </tr>
    <tr>
        @for (var i = 0; i < data.Count(); i++)
        {
            <td>@Model.Events[data[i].ToString()].Core.Updated</td>
            <td>@Model.Events[data[i].ToString()].Core.UpdatedTs</td>
            <td>@Model.Events[data[i].ToString()].Info.Points</td>
            <td>@Model.Events[data[i].ToString()].Info.Score</td>
            //more property...
        }
    </tr>  
</table>

注意:这种方式在视图中显示数据并不容易且复杂。如果您不想更改模型。我建议您也可以生成如下所示的json文件,因为你只有一个Event(public Events Events { get; set; } ) 在您的Goalserve 模型中:

{
  "updated": "15.12.2019 23:30:52",
  "updated_ts": 1576449052,
  "events": {
    "84586848": {
      "core": {
        "safe": 0,
        "stopped": 0,
        "blocked": 0,
        "finished": 0,
        "updated": "2019-12-15 23:31:02",
        "updated_ts": 1576452662
      },
      "info": {
        //...
      },
      "stats": {
        "0": {
          "name": "ITeam",
          "home": "Five Islands",
          "away": "Pigotts Bullets FC"
        },
        "1": {
          "name": "IGoal",
          "home": "0",
          "away": "0"
        }
      },
      "odds": {
        "0": {
         // ...
          }
        },
        "1": {
          //...
      }
    }
  }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-06-08
    • 1970-01-01
    • 2020-08-31
    • 1970-01-01
    • 1970-01-01
    • 2018-10-07
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多