如何使用列表<object>来响应 API - C# Xamarin



我正在尝试转换此JSON API(http://194.141.118.43:3000/?date=2022-03-22&id=400&daysForward=8(到C#对象: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("ttERROR {0}", ex.Message);
}
return weatherData;
}

此行不正确:

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

如何在此处使用此列表?

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

更新

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

对象类看起来像:

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类看起来像:

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("ttERROR {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:UsersAdminDesktoppizhevsoftpizhevsoftpizhevsoftpizhevsoftServicesRestServiceAPI.cs:30 }

此行不正确:

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

事实上,这是一个语法错误,应该在List:周围有<>

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("ttERROR {0}", ex.Message);
}
return null;
}

但我认为你应该看看戴的推荐信;自动工具显然正在努力反向工程这个比正常JSON块更古怪的任务(我个人从未见过QT生成像这里这样的东西-这显然是QT开发人员预见到的一个用例,所以如果你对此感到满意/不觉得有OA规范会提供更有用的东西…(

相关内容

  • 没有找到相关文章

最新更新