如何使用 List<object> 响应 API - C# Xamarin

How to use List<object> in response to API - C# Xamarin

我正在尝试转换这个 JSON API (http://194.141.118.43:3000/?date=2022-03-22&id=400&daysForward=8) to C# object here: https://json2csharp.com/

我收到了List<object> aladinModel { get; set; }

如何在我对 API 的回复中使用此列表 aladinModel:

 public async Task List<AladinModel> GetWeatherData(string query)
    {
        List<AladinModel> weatherData = new List<AladinModel>();
        try
        {
            var response = await _client.GetAsync(query);
            if (response.IsSuccessStatusCode)
            {
                var content = await response.Content.ReadAsStringAsync();
                weatherData = JsonConvert.DeserializeObject<AladinModel>(content);
            }
        }
        catch (Exception ex)
        {
            Debug.WriteLine("\t\tERROR {0}", ex.Message);
        }

        return weatherData;
    }

这行不正确:

public async Task List<AladinModel> GetWeatherData(string query)

如何在这里使用这个列表?

============================================= ==================

更新

============================================= ==================

对象 class 看起来像:

 class ItemsAPI
{
    public partial class RootAladinModel
    {
        [JsonProperty("aladinModel")]
        public AladinModel[] AladinModel { get; set; }
    }

    public partial class AladinModel
    {
        [JsonProperty("DATS")]
        public DateTimeOffset Dats { get; set; }

        [JsonProperty("TA")]
        public double Ta { get; set; }

        [JsonProperty("RH")]
        public double Rh { get; set; }

        [JsonProperty("WS")]
        public double Ws { get; set; }

        [JsonProperty("RR")]
        public double Rr { get; set; }

        [JsonProperty("SR")]
        public double Sr { get; set; }

        [JsonProperty("APRES")]
        public double Apres { get; set; }
    }
}

RestService class 看起来像:

 public async Task<List<AladinModel>> GetAladinData(string query)
    {
        List<AladinModel> weatherData = new List<AladinModel>();
        try
        {
            var response = await _client.GetAsync(query);
            if (response.IsSuccessStatusCode)
            {
                var content = await response.Content.ReadAsStringAsync();
                weatherData = JsonConvert.DeserializeObject<List<AladinModel>>(content);
            }
        }
        catch (Exception ex)
        {
            Debug.WriteLine("\t\tERROR {0}", ex.Message);
        }

        return weatherData;
    }

但我收到错误消息:

    {Newtonsoft.Json.JsonSerializationException: Cannot deserialize the current JSON object (e.g. {"name":"value"}) into type 'System.Collections.Generic.List`1[pizhevsoft.Models.ItemsAPI+AladinModel]' because the type requires a JSON array (e.g. [1,2,3]) to deserialize correctly.
To fix this error either change the JSON to a JSON array (e.g. [1,2,3]) or change the deserialized type so that it is a normal .NET type (e.g. not a primitive type like integer, not a collection type like an array or List<T>) that can be deserialized from a JSON object. JsonObjectAttribute can also be added to the type to force it to deserialize from a JSON object.
Path 'aladinModel', line 1, position 15.
  at Newtonsoft.Json.Serialization.JsonSerializerInternalReader.CreateObject (Newtonsoft.Json.JsonReader reader, System.Type objectType, Newtonsoft.Json.Serialization.JsonContract contract, Newtonsoft.Json.Serialization.JsonProperty member, Newtonsoft.Json.Serialization.JsonContainerContract containerContract, Newtonsoft.Json.Serialization.JsonProperty containerMember, System.Object existingValue) [0x003a0] in <7ca8898b690a4181a32a9cf767cedb1e>:0 
  at Newtonsoft.Json.Serialization.JsonSerializerInternalReader.CreateValueInternal (Newtonsoft.Json.JsonReader reader, System.Type objectType, Newtonsoft.Json.Serialization.JsonContract contract, Newtonsoft.Json.Serialization.JsonProperty member, Newtonsoft.Json.Serialization.JsonContainerContract containerContract, Newtonsoft.Json.Serialization.JsonProperty containerMember, System.Object existingValue) [0x0006d] in <7ca8898b690a4181a32a9cf767cedb1e>:0 
  at Newtonsoft.Json.Serialization.JsonSerializerInternalReader.Deserialize (Newtonsoft.Json.JsonReader reader, System.Type objectType, System.Boolean checkAdditionalContent) [0x000db] in <7ca8898b690a4181a32a9cf767cedb1e>:0 
  at Newtonsoft.Json.JsonSerializer.DeserializeInternal (Newtonsoft.Json.JsonReader reader, System.Type objectType) [0x00054] in <7ca8898b690a4181a32a9cf767cedb1e>:0 
  at Newtonsoft.Json.JsonSerializer.Deserialize (Newtonsoft.Json.JsonReader reader, System.Type objectType) [0x00000] in <7ca8898b690a4181a32a9cf767cedb1e>:0 
  at Newtonsoft.Json.JsonConvert.DeserializeObject (System.String value, System.Type type, Newtonsoft.Json.JsonSerializerSettings settings) [0x0002d] in <7ca8898b690a4181a32a9cf767cedb1e>:0 
  at Newtonsoft.Json.JsonConvert.DeserializeObject[T] (System.String value, Newtonsoft.Json.JsonSerializerSettings settings) [0x00000] in <7ca8898b690a4181a32a9cf767cedb1e>:0 
  at Newtonsoft.Json.JsonConvert.DeserializeObject[T] (System.String value) [0x00000] in <7ca8898b690a4181a32a9cf767cedb1e>:0 
  at pizhevsoft.Services.RestServiceAPI.GetAladinData (System.String query) [0x00151] in C:\Users\Admin\Desktop\pizhevsoft\pizhevsoft\pizhevsoft\pizhevsoft\Services\RestServiceAPI.cs:30 }

This line is not correct:

public async Task List<AladinModel> GetWeatherData(string query)

的确,这是一个语法错误,列表周围应该有<>

public async Task<List<AladinModel>> GetWeatherData(string query)

看来 json2csharp 不能很好地理解 JSON。 QuickType.io 更复杂:

// <auto-generated />
//
// To parse this JSON data, add NuGet 'Newtonsoft.Json' then do:
//
//    using SomeNamespace;
//
//    var someRootClassName = SomeRootClassName.FromJson(jsonString);

namespace SomeNamespace
{
    using System;
    using System.Collections.Generic;

    using System.Globalization;
    using Newtonsoft.Json;
    using Newtonsoft.Json.Converters;

    public partial class SomeRootClassName
    {
        [JsonProperty("aladinModel")]
        public List<AladinModelUnion> AladinModel { get; set; }
    }

    public partial class PurpleAladinModel
    {
        [JsonProperty("DATS")]
        public DateTimeOffset Dats { get; set; }

        [JsonProperty("TA")]
        public double Ta { get; set; }

        [JsonProperty("RH")]
        public double Rh { get; set; }

        [JsonProperty("WS")]
        public double Ws { get; set; }

        [JsonProperty("RR")]
        public double Rr { get; set; }

        [JsonProperty("SR")]
        public double Sr { get; set; }

        [JsonProperty("APRES")]
        public double Apres { get; set; }
    }

    public partial class FluffyAladinModel
    {
        [JsonProperty("fieldCount")]
        public long FieldCount { get; set; }

        [JsonProperty("affectedRows")]
        public long AffectedRows { get; set; }

        [JsonProperty("insertId")]
        public long InsertId { get; set; }

        [JsonProperty("serverStatus")]
        public long ServerStatus { get; set; }

        [JsonProperty("warningCount")]
        public long WarningCount { get; set; }

        [JsonProperty("message")]
        public string Message { get; set; }

        [JsonProperty("protocol41")]
        public bool Protocol41 { get; set; }

        [JsonProperty("changedRows")]
        public long ChangedRows { get; set; }
    }

    public partial struct AladinModelUnion
    {
        public FluffyAladinModel FluffyAladinModel;
        public List<PurpleAladinModel> PurpleAladinModelArray;

        public static implicit operator AladinModelUnion(FluffyAladinModel FluffyAladinModel) => new AladinModelUnion { FluffyAladinModel = FluffyAladinModel };
        public static implicit operator AladinModelUnion(List<PurpleAladinModel> PurpleAladinModelArray) => new AladinModelUnion { PurpleAladinModelArray = PurpleAladinModelArray };
    }

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

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

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

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

        public override object ReadJson(JsonReader reader, Type t, object existingValue, JsonSerializer serializer)
        {
            switch (reader.TokenType)
            {
                case JsonToken.StartObject:
                    var objectValue = serializer.Deserialize<FluffyAladinModel>(reader);
                    return new AladinModelUnion { FluffyAladinModel = objectValue };
                case JsonToken.StartArray:
                    var arrayValue = serializer.Deserialize<List<PurpleAladinModel>>(reader);
                    return new AladinModelUnion { PurpleAladinModelArray = arrayValue };
            }
            throw new Exception("Cannot unmarshal type AladinModelUnion");
        }

        public override void WriteJson(JsonWriter writer, object untypedValue, JsonSerializer serializer)
        {
            var value = (AladinModelUnion)untypedValue;
            if (value.PurpleAladinModelArray != null)
            {
                serializer.Serialize(writer, value.PurpleAladinModelArray);
                return;
            }
            if (value.FluffyAladinModel != null)
            {
                serializer.Serialize(writer, value.FluffyAladinModel);
                return;
            }
            throw new Exception("Cannot marshal type AladinModelUnion");
        }

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

要使用它,您可能需要这样的代码:

public async Task<List<AladinModelUnion>> GetAladinData(string query)
{
    try
    {
        var response = await _client.GetAsync(query);
        if (response.IsSuccessStatusCode)
        {
            var content = await response.Content.ReadAsStringAsync();
            var someRootClassName = SomeRootClassName.FromJson(jsonString);
            return someRootClassName.AladinModel;
        }
    }
    catch (Exception ex)
    {
        Debug.WriteLine("\t\tERROR {0}", ex.Message);
    }

    return null;
}

但我确实认为你应该看看戴在这里的推荐; auto-tools 显然正在努力完成 JSON 的 rather-more-wacky-than-normal 块的逆向工程任务(我个人从未见过 QT 生成像这里那样的任何东西 - 这显然是QT 开发人员,所以如果您对 it/don 感到满意,那么没有 OA 规范会提供更多帮助...)