0

I'm trying to display json data after deserialization in a .net core 2.0 app. The JSON file is sended by POST request each 1-3 seconds to my server by my feed provider (He push data to my server)

This is what i'm doing:

  1. I treat a gzip file sended by POST request and unzip the json file inside it and download it on my server (DONE)

  2. Now, i'm trying to read this json file and display it on the first page "index.cshtml". We will create a new line for each POST request sended by the feed provider --> lines are displayed in realtime line after line (NOT DONE YET)

INDEX.XSHTML Example of View

1- FIRST LINE = "info":{"id":84844481,"name":"Five Islands vs Pigotts Bullets FC","sport":"Soccer","league":"Antigua and Barbuda Premier Division","start_time":"22:11","start_date":"15.12.2019","start_ts":1576444268,"period":"2nd Half","minute":"73","secunds":"72:54","score":"0:0","points":"","pitch":"","ball_pos":"","add_time":"","player":"","state":"21012"}

2- SECOND LINE = "info":{"id":84844482,"name":"xxxx vs xxxx FC","sport":"Soccer","league":"SERIE A","start_time":"22:30","start_date":"15.12.2019","start_ts":1576444268,"period":"2nd Half","minute":"18","secunds":"18:54","score":"0:0","points":"","pitch":"","ball_pos":"0.71, 0.48","add_time":"","player":"hoffman","state":"21000"} 3- ETC. ....

PS : Here I just copied the info tag as it is => SURE I need well formatted info such : 1- FIRST LINE : id = xxxxx, name="", ....

This is an example of the JSON feed : https://filebin.net/k5enw2wn4f5bc89m/inplay-soccer.json?t=84y0df94

This is my code until now :

ValuesController

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>

        [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);
                }

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

Goalserve model (I generated it with https://app.quicktype.io/) --> maybe some problems here !

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.xshtml

@page
@model HelloWorld.Models.Goalserve
@{
    var objects = Model;
}
<table>
    <tr>
        test
        <td>@objects.ToString()</td>
    </tr>
</table>

Can someone help me please to implement this .net app ?

I'm sure there are some concepts/models out there that I'm not familiar with and I'd be very grateful if someone can help me to implement this code.

Thank you very much for any help!

1 Answer 1

1

You can use LINQ to query a JSON file. Refer: SelectToken

var jobject = JObject.Parse(json);
var results = jobject.SelectTokens("$..info");
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.