Как объединить [JsonPropertyName] и [ObservableProperty] в одном элементе?C#

Место общения программистов C#
Ответить
Anonymous
 Как объединить [JsonPropertyName] и [ObservableProperty] в одном элементе?

Сообщение Anonymous »

Я пытаюсь объединить [JsonPropertyName] с [ObservableProperty], чтобы присвоить значение «last_updated» моего json свойству «Обновлено» моего объекта.
Я попробовал этот код:
[ObservableProperty]
[JsonPropertyName("last_updated")]
public string updated;

Но он не работает: после десериализации значение «Обновлено» равно нулю.
Каков должен быть правильный способ справиться с этим?
Пример моего JSON:
[{"id":1,"username":"******","password":"******","email":"*****","created":"2023-12-19 19:28:23","last_updated":"2023-12-19 19:28:23","address":"*******","full_name":"*******","last_login":{"id":1,"user_id":1,"ip_address":"******","result_code":"0","result":"Success"},"role":"Admin"}]

Подробности проекта:
  • WinUI 3
  • System.Text.Json 8.0.0
  • CommunityToolkit.Mvvm 8.2.2
  • .NET 6.0
Добавляю скриншот, показывающий проверку:
Изображение

Полный код класса:
using CommunityToolkit.Mvvm.ComponentModel;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Text.Json.Serialization;
using System.Threading.Tasks;

namespace RotaPro.Models;

public partial class Dipendente : ObservableObject
{

[ObservableProperty]
private int id;

[ObservableProperty]
private string username;

[ObservableProperty]
private string email;

[ObservableProperty]
private string created;

[ObservableProperty]
[JsonPropertyName("last_updated")]
public string updated;

[ObservableProperty]
private string address;

[ObservableProperty]
[JsonPropertyName("full_name")]
private string fullName;

public Dipendente()
{

}

public Dipendente(int id, string username, string email, string created, string updated, string address, string fullName)
{
Id = id;
Username = username;
Email = email;
Created = created;
Updated = updated;
Address = address;
FullName = fullName;
}

public override string ToString()
{
return FullName;
}

}

Код десериализации:
using Microsoft.UI.Xaml.Media.Animation;
using RestSharp;
using RestSharp.Authenticators;
using RotaPro.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Text.Json;
using System.Net;
using System.Net.Http;
using Serilog;

namespace RotaPro.Classes;

public class ApiClient
{

private static RestClient _instance;
private static bool _initialized = false;

public ApiClient()
{

}

public void Initialize(string username, string apiKey)
{
if (_instance is not null)
throw new InvalidOperationException("ApiClient già inizializzato");

RestClientOptions options = new RestClientOptions("https://*****/***/**/")
{
Authenticator = new HttpBasicAuthenticator(username, apiKey)
};

_instance = new RestClient(options);
_initialized = true;
}

public static async Task GetDipendenti()
{
if (!_initialized)
throw new InvalidOperationException("ApiClient non inizializzato");

RestRequest request = new RestRequest("/user/all");
RestResponse response = await _instance.ExecuteAsync(request);

if(!response.StatusCode.Equals(HttpStatusCode.OK))
{
throw new HttpRequestException($"Errore {response.StatusCode} durante la richiesta");
}

string json = response.Content;
Log.Debug($"Ricevuto: {json}");

JsonSerializerOptions options = new JsonSerializerOptions
{
PropertyNameCaseInsensitive = true
};

List lista = JsonSerializer.Deserialize(json, options)!;

return lista;
}

}



Подробнее здесь: https://stackoverflow.com/questions/776 ... ame-member
Ответить

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

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

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

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

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