如何处理变化的JSON?

cptalpdeniz

由于我是新手,对您的无知感到抱歉。我需要检查是否有抽搐直播。我正在通过使用HttpClient和GET请求来做到这一点TwitchData以下是将JSON反序列化为对象的类

public partial class TwitchData
{
    [JsonProperty("data")]
    public Datum[] Data { get; set; }

    [JsonProperty("pagination")]
    public Pagination Pagination { get; set; }
}

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

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

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

    [JsonProperty("community_ids")]
    public object[] CommunityIds { get; set; }

    [JsonProperty("type")]
    public string Type { get; set; }

    [JsonProperty("title")]
    public string Title { get; set; }

    [JsonProperty("viewer_count")]
    public long ViewerCount { get; set; }

    [JsonProperty("started_at")]
    public DateTimeOffset StartedAt { get; set; }

    [JsonProperty("language")]
    public string Language { get; set; }

    [JsonProperty("thumbnail_url")]
    public string ThumbnailUrl { get; set; }
}

public partial class Pagination
{
    [JsonProperty("cursor")]
    public string Cursor { get; set; }
}

public partial class TwitchData
{
    public static TwitchData FromJson(string json) => JsonConvert.DeserializeObject<TwitchData>(json, QuickType.Converter.Settings);
}

public static class Serialize
{
    public static string ToJson(this TwitchData self) => JsonConvert.SerializeObject(self, QuickType.Converter.Settings);
}

internal static class Converter
{
    public static readonly JsonSerializerSettings Settings = new JsonSerializerSettings
    {
        MetadataPropertyHandling = MetadataPropertyHandling.Ignore,
        DateParseHandling = DateParseHandling.None,
        Converters = {
            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();
}

我对此提出要求

HttpClient client = new HttpClient();
string uri = "https://api.twitch.tv/helix/streams?user_id=59980349";
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Client-ID", token);
var result = client.GetStringAsync(uri);
jsonString = result.ToString();
twitchData = PwdResetRequest.FromJson(jsonString);

这样做的问题是,如果流脱机,则JSON会更改,从而使编写的类TwitchData无法用于JsonConvert.DeserializeObject。

以下是流在线和离线时的JSON。

{
  "data": [
    {
      "id": "30356128676",
      "user_id": "59788312",
      "game_id": "498652",
      "community_ids": [],
      "type": "live",
      "title": "A stream",
      "viewer_count": 1325,
      "started_at": "2018-09-07T16:30:09Z",
      "language": "en",
      "thumbnail_url": "url"
    }
  ],
  "pagination": {
    "cursor": "eydBIjpwdWGsLaJhIjp7IkGH4hNl6CH6MXr9"
  }
}

当它离线时

{
  "data": [],
  "pagination": {}
}
cptalpdeniz

我找到了解决问题的办法。我正在创建的对象具有2个变量,Datum[] dataPagination Pagination坦白说,如果流处于脱机状态,则JSON字符串中唯一的变化(可以在问题中看到)是数据数组和分页块均为空。通过检查这些变量的长度条件(检查其中一个就足够了),我可以确定流是实时的还是离线的。例如getStreams上课

if (getStreams.Datum.Length != 0) {
return true;
}
else {
return false;
}

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章