BJSON - Esempi
Serializzazione e deserializzazione
using B.BStatics;
UserSetting setting = new UserSetting
{
Name = "Marco",
Enabled = true
};
string json = BJSON.Serialize(setting);
UserSetting? restoredSetting = BJSON.Deserialize<UserSetting>(json);
public class UserSetting
{
public string Name { get; set; } = "";
public bool Enabled { get; set; }
}
Se non vengono specificate opzioni, BJSON utilizza DefaultOptions, che produce JSON indentato e converte le enumerazioni in stringhe.
Lettura di un valore
using B.BStatics;
string json = """
{
"ApplicationName": "BStudio"
}
""";
string? applicationName = BJSON.GetValueFromJsonText(json, "ApplicationName");
GetValueFromJsonText restituisce null quando il testo non è valido o la chiave non viene trovata.
Lettura tipizzata di un valore annidato
using B.BStatics;
string json = """
{
"details": {
"context_length": 8192,
"enabled": true
}
}
""";
int contextLength = BJSON.GetValue<int>(json, "details.context_length");
bool enabled = BJSON.GetValue<bool>(json, "DETAILS.ENABLED");
Il percorso usa il punto per attraversare oggetti JSON annidati e i nomi delle proprietà non distinguono maiuscole e minuscole. Se il percorso non esiste, il JSON non è valido o il valore non può essere convertito nel tipo richiesto, il metodo restituisce il valore predefinito del tipo (null, 0, false e così via).
