skip to Main Content

I’m trying to combine [JsonPropertyName] with [ObservableProperty] to assign the value "last_updated" of my json to the property "Updated" of my object.

I tried this code:

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

But it is not working: ‘Updated’ is null after deserializing.

What should be the correct way to handle this?

An example of my 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"}]

Project details:

  • WinUI 3
  • System.Text.Json 8.0.0
  • CommunityToolkit.Mvvm 8.2.2
  • .NET 6.0

I add a screenshot showing the inspection:

Screenshot of debugger

Full class code:

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

}

Deserialization code:

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

}

2

Answers


  1. just include in options IncludeFields and you will be happy

    JsonSerializerOptions options = new JsonSerializerOptions
        {
            PropertyNameCaseInsensitive = true,
            IncludeFields=true
        };
    
        List<Dipendente> lista = JsonSerializer.Deserialize<List<Dipendente>>(json, options)!;
    

    but you will have to make all fields public

    Login or Signup to reply.
  2. The CommunityToolkit.Mvvm support this. So you should be able to add attributes like this:

    [ObservableProperty]
    [property: JsonPropertyName("last_updated")]
    public string updated;
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search