Невозможно десериализовать текущий объект JSON (например, {"name":"value"}) в тип 'DAL.vehicleInfo[] [дубликат]C#

Место общения программистов C#
Ответить Пред. темаСлед. тема
Anonymous
 Невозможно десериализовать текущий объект JSON (например, {"name":"value"}) в тип 'DAL.vehicleInfo[] [дубликат]

Сообщение Anonymous »

мы создаем клиент API для отдыха, который возвращает что-то вроде этого:

Код: Выделить всё

{
"uniqueID": 123456789,
"plate": "0123456789ABCD",
"GPSDate": "2021-04-13T07:38:24Z",
"latitude": 43.12345,
"longitude": -3.12345,
"speed": 120,
"course": 325,
"odometer": 205486.732,
"receivedDate": "2021-04-13T07:38:24Z",
"stateInfo": {
"stateData": {
"stateParam": "50+",
"stateDetail": "12345"
}
},
"GPSQuality": 1,
"CANInfo": {
"CANData": {
"CANParam": "RPM",
"CANValue": "3250"
}
},
"peripheralsInfo": {
"peripheralsData": {
"peripheralsParam": "Motor",
"peripheralsValue": "En marcha"
}
},
"geofenceInfo": {
"geofenceData": {
"geofencePoint": "Punto 1",
"geofencePolygon": "Geocerca Poligonal 1"
}
}
}
Для этого создадим следующие классы:

Код: Выделить всё

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace DAL
{
public class CANData
{
public string? CANParam { get; set; }
public string? CANValue { get; set; }
}
}

namespace DAL
{
public class geofenceData
{
public string? geofencePoint { get; set; }
public string? geofencePolygon { get; set; }
}
}

namespace DAL
{
public class peripheralsData
{
public string? peripheralsParam { get; set; }
public string? peripheralsValue { get; set; }
}
}

namespace DAL
{
public class stateData
{
public string? stateParam { get; set; }
public string? stateDetail { get; set; }
}
}

namespace DAL
{
public class vehicleInfo
{
public long uniqueID { get; set; }
public string? plate { get; set; }
public DateTime GPSDate { get; set; }
public float latitude { get; set; }
public float longitude { get; set; }
public int speed { get; set; }
public int course { get; set; }
public float odometer { get; set; }
public DateTime receivedDate { get; set; }
public stateData[]? stateInfo { get; set; }
public int GPSQuality { get; set; }
public CANData[]? CANInfo { get; set; }
public peripheralsData[]? peripheralsInfo { get; set; }
public geofenceData? geofenceInfo { get; set; }
}
}
Вот методы, которые мы используем:

Код: Выделить всё

using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Microsoft.Extensions.Configuration;
using DAL;

namespace BIL
{
public class FlotasNetClient
{
private static string? _baseUrl;
private static string? _username;
private static string? _sha256Concatenado;
private static string? _company;

public FlotasNetClient()
{
var builder = new ConfigurationBuilder().SetBasePath(Directory.GetCurrentDirectory()).AddJsonFile("appsettings.json").Build();

_baseUrl = builder.GetSection("baseUrl").Value;
_username = builder.GetSection("username").Value;
_sha256Concatenado = builder.GetSection("sha256Concatenado").Value;
_company = builder.GetSection("company").Value;
}

public async Task  GetVehicleInfoByDate()
{
var client = new HttpClient();
var request = new HttpRequestMessage
{

Method = HttpMethod.Get,
RequestUri = new Uri("https://servicios.flotasnet.es:1443/api/GetInfoVehicleByDate2?startdate=2024-10-09T01%3A00%3A00Z&enddate=2024-10-09T01%3A05%3A00Z"),
Headers =
{
{ "user-agent", "vscode-restclient" },
{ "accept", "application/json" },
{ "user", _username },
{ "password", _sha256Concatenado },
{ "company", _company },
},
};
using (var response = await client.SendAsync(request))
{
response.EnsureSuccessStatusCode();
var body = await response.Content.ReadAsStringAsync();
Console.WriteLine(body);
var Deserialized = JsonConvert.DeserializeObject(body);
return Deserialized;
}
}
}
}
Это файл program.cs:

Код: Выделить всё

using BIL;
using Newtonsoft.Json;

var client = new FlotasNetClient();
var vehicleData = await client.GetVehicleInfoByDate();
Во время компиляции возникает эта ошибка:

Код: Выделить всё

Newtonsoft.Json.JsonSerializationException: 'Cannot deserialize the current JSON object (e.g. {"name":"value"}) into type 'DAL.vehicleInfo[]' 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) 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 'message', line 1, position 11.'
Увидев ошибку, мы изменили тип данных с VehicleInfo[] на List, но ошибка продолжала появляться во время компиляции.

Код: Выделить всё

Newtonsoft.Json.JsonSerializationException: 'Cannot deserialize the current JSON object (e.g. {"name":"value"}) into type 'System.Collections.Generic.List`1[DAL.vehicleInfo]' 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) 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 'message', line 1, position 11.'
Мы ценим вашу поддержку

Подробнее здесь: https://stackoverflow.com/questions/790 ... to-type-da
Реклама
Ответить Пред. темаСлед. тема

Быстрый ответ

Изменение регистра текста: 
Смайлики
:) :( :oops: :roll: :wink: :muza: :clever: :sorry: :angel: :read: *x)
Ещё смайлики…
   
К этому ответу прикреплено по крайней мере одно вложение.

Если вы не хотите добавлять вложения, оставьте поля пустыми.

Максимально разрешённый размер вложения: 15 МБ.

  • Похожие темы
    Ответы
    Просмотры
    Последнее сообщение

Вернуться в «C#»