繁体   English   中英

如何使用清单<object>回应 API - C# Xamarin<div id="text_translate"><p> I trying to convert this JSON API ( <a href="http://194.141.118.43:3000/?date=2022-03-22&id=400&daysForward=8" rel="nofollow noreferrer">http://194.141.118.43:3000/?date=2022-03-22&id=400&daysForward=8</a> ) to C# object here: <a href="https://json2csharp.com/" rel="nofollow noreferrer">https://json2csharp.com/</a></p><p> 我收到List<object> aladinModel { get; set; } List<object> aladinModel { get; set; }</p><p> 如何在我对 API 的回复中使用此列表 aladinModel:</p><pre> 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; }</pre><p> 此行不正确:</p><pre> public async Task List<AladinModel> GetWeatherData(string query)</pre><p> 如何在这里使用这个列表?</p><p> ================================================ =============</p><p> <strong>更新</strong></p><p> ================================================ =============</p><p> object class 看起来像:</p><pre> 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; } } }</pre><p> RestService class 看起来像:</p><pre> 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; }</pre><p> 但我收到错误:</p><pre> {Newtonsoft.Json.JsonSerializationException: Cannot deserialize the current JSON object (eg {"name":"value"}) into type 'System.Collections.Generic.List`1[pizhevsoft.Models.ItemsAPI+AladinModel]' because the type requires a JSON array (eg [1,2,3]) to deserialize correctly. To fix this error either change the JSON to a JSON array (eg [1,2,3]) or change the deserialized type so that it is a normal .NET type (eg 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 }</pre></div></object>

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

I trying to convert this 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; } 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)

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

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

更新

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

object 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 }

此行不正确:

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

事实上,这是一个语法错误,列表周围应该有<>

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

看起来 json2csharp 不能很好地理解 JSON。 QuickType.io 有一个更复杂的 go:

// <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;
}

但我确实认为你应该在这里看看 Dai 的推荐; auto-tools 显然正在努力完成逆向工程这个比正常块更古怪的 JSON 的任务(我从来没有亲眼看到 QT 生成像它在这里生成的任何东西 - 这显然是 QT 开发人员预见的一个用例不过,如果您对此感到满意/不觉得拥有 OA 规范会提供更多帮助...)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM