如何在同一成员上合并[JsonPropertyName]和[ObservableProperty]?

s1ag04yj  于 5个月前  发布在  其他
关注(0)|答案(2)|浏览(44)

我尝试将合并[JsonPropertyName][ObservableProperty]结合起来,将json的值“last_updated”赋给对象的属性“Updated”。
我试了这个代码:

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

字符串
但是它不起作用:'Updated'在格式化后为null。
正确的处理方法应该是什么?
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<List<Dipendente>> 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<Dipendente> lista = JsonSerializer.Deserialize<List<Dipendente>>(json, options)!;

        return lista;
    }

}

bcs8qyzn

bcs8qyzn1#

CommunityToolkit.Mvvm支持this,所以你应该可以像这样添加属性:

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

字符串

i7uq4tfw

i7uq4tfw2#

只要包括在选项IncludeFields中,您就会很高兴

JsonSerializerOptions options = new JsonSerializerOptions
    {
        PropertyNameCaseInsensitive = true,
        IncludeFields=true
    };

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

字符串
但你必须公开所有字段

相关问题