Una colección de extensión para .NET System.text.json
Un JsonConverter que deserializa un solo objeto JSON y una matriz JSON como una matriz C#.
public sealed class Example
{
[ JsonConverter ( typeof ( SingleOrArrayJsonConverter ) ) ]
public string [ ] ? Array { get ; set ; }
} const string jsonSingle = """{"Array": "single"}""" ;
var deserializedSingle = JsonSerializer . Deserialize < Example > ( jsonSingle ) ;
Console . WriteLine ( $ " { deserializedSingle . Array . Length } : { deserializedSingle . Array [ 0 ] } " ) ;
// Output: "1: single"
const string jsonArray = """{"Array": ["first", "second"]}""" ;
var deserializedArray = JsonSerializer . Deserialize < Example > ( jsonArray ) ;
Console . WriteLine ( $ " { deserializedArray . Array . Length } : { deserializedArray . Array [ 0 ] } , { deserializedArray . Array [ 1 ] } " ) ;
// Output: "2: first, second" public sealed class Person
{
public string FirstName { get ; }
public string LastName { get ; }
public Person ( string firstName , string lastName )
{
FirstName = firstName ;
LastName = lastName ;
}
}
// Converts a Person object into a "${FirstName} ${LastName}" string
public sealed class PersonJsonConverter : JsonConverter < string >
{
public override string ? Read ( ref Utf8JsonReader reader , Type typeToConvert , JsonSerializerOptions options )
{
var personConverter = ( JsonConverter < Person > ) options . GetConverter ( typeof ( Person ) ) ;
Person ? person = personConverter . Read ( ref reader , typeof ( Person ) , options ) ;
return person != null ? $ " { person . FirstName } { person . LastName } " : null ;
}
public override void Write ( Utf8JsonWriter writer , string value , JsonSerializerOptions options )
{
var personConverter = ( JsonConverter < Person > ) options . GetConverter ( typeof ( Person ) ) ;
var split = value . Split ( ' ' ) ;
var firstName = split [ 0 ] ;
var lastName = split [ 1 ] ;
var person = new Person ( firstName , lastName ) ;
personConverter . Write ( writer , person , options ) ;
}
}
public sealed class Example
{
[ JsonConverter ( typeof ( SingleOrArrayJsonConverter < PersonJsonConverter > ) ) ]
public string [ ] ? Array { get ; set ; }
} const string jsonSingle = """{"Array": {"FirstName": "John", "LastName": "Smith"}}""" ;
var deserializedSingle = JsonSerializer . Deserialize < Example > ( json ) ;
Console . WriteLine ( $ " { deserializedSingle . Array . Length } : { deserializedSingle . Array [ 0 ] } " ) ;
// Output: "1: John Smith"
const string jsonArray = """{"Array": [{"FirstName": "John", "LastName": "Smith"}, {"FirstName": "John", "LastName": "Doe"}]}""" ;
var deserializedArray = JsonSerializer . Deserialize < Example > ( json ) ;
Console . WriteLine ( $ " { deserializedArray . Array . Length } : { deserializedArray . Array [ 0 ] } , { deserializedArray . Array [ 1 ] } " ) ;
// Output: "2: John Smith, John Doe" Un atributo JSONPropertynames y JSONMultInamEmodifier que permite el mapeo de múltiples claves JSON a una propiedad C#.
public sealed class User
{
[ JsonPropertyNames ( "UserName" , "User" , "Name" ) ]
public string UserName { get ; set ; }
} JsonSerializerOptions jsonOptions = new ( )
{
TypeInfoResolver = new DefaultJsonTypeInfoResolver ( )
{
Modifiers = { Modifiers . JsonMultiNameModifier }
}
}
const string json1 = """{"UserName": "JohnSmith1"}""" ;
const string json2 = """{"User": "JohnSmith2"}""" ;
const string json3 = """{"Name": "JohnSmith3"}""" ;
var deserialized = JsonSerializer . Deserialize < User > ( json1 , jsonOptions ) ;
Console . WriteLine ( deserialized . UserName ) ;
// Output: "JohnSmith1"
deserialized = JsonSerializer . Deserialize < User > ( json2 , jsonOptions ) ;
Console . WriteLine ( deserialized . UserName ) ;
// Output: "JohnSmith2"
deserialized = JsonSerializer . Deserialize < User > ( json3 , jsonOptions ) ;
Console . WriteLine ( deserialized . UserName ) ;
// Output: "JohnSmith3"
string json = """{"UserName": "JohnSmith1", "User": "JohnSmith2", "Name": "JohnSmith3"}""" ;
deserialized = JsonSerializer . Deserialize < User > ( json , jsonOptions ) ;
Console . WriteLine ( deserialized . UserName ) ;
// Output: "JohnSmith3"
json = JsonSerializer . Serialize ( deserialized , jsonOptions ) ;
Console . WriteLine ( json ) ;
// Output: '{"UserName":"JohnSmith3"}' public sealed class User
{
[ JsonPropertyNames ( throwOnDuplicate : true , "UserName" , "User" , "Name" ) ]
public string UserName { get ; set ; }
} JsonSerializerOptions jsonOptions = new ( )
{
TypeInfoResolver = new DefaultJsonTypeInfoResolver ( )
{
Modifiers = { Modifiers . JsonMultiNameModifier }
}
}
const string json1 = """{"UserName": "JohnSmith1"}""" ;
const string json2 = """{"User": "JohnSmith2"}""" ;
const string json3 = """{"Name": "JohnSmith3"}""" ;
var deserialized = JsonSerializer . Deserialize < User > ( json1 , jsonOptions ) ;
Console . WriteLine ( deserialized . UserName ) ;
// Output: "JohnSmith1"
deserialized = JsonSerializer . Deserialize < User > ( json2 , jsonOptions ) ;
Console . WriteLine ( deserialized . UserName ) ;
// Output: "JohnSmith2"
deserialized = JsonSerializer . Deserialize < User > ( json3 , jsonOptions ) ;
Console . WriteLine ( deserialized . UserName ) ;
// Output: "JohnSmith3"
try {
const string json = """{"UserName": "JohnSmith1", "User": "JohnSmith2", "Name": "JohnSmith3"}""" ;
deserialized = JsonSerializer . Deserialize < User > ( json , jsonOptions ) ;
Console . WriteLine ( deserialized . UserName ) ;
} catch ( JsonException ) {
Console . WriteLine ( "Deserialize failed" ) ;
}
// Output: "Deserialize failed" public sealed class User
{
[ JsonPropertyNames ( serializationName : "NickName" , "UserName" , "User" , "Name" ) ]
public string UserName { get ; set ; }
} JsonSerializerOptions jsonOptions = new ( )
{
TypeInfoResolver = new DefaultJsonTypeInfoResolver ( )
{
Modifiers = { Modifiers . JsonMultiNameModifier }
}
}
string json = """{"UserName": "JohnSmith"}""" ;
var deserialized = JsonSerializer . Deserialize < User > ( json , jsonOptions ) ;
Console . WriteLine ( deserialized . UserName ) ;
// Output: "JohnSmith"
json = JsonSerializer . Serialize ( deserialized , jsonOptions ) ;
Console . WriteLine ( json ) ;
// Output: '{"NickName":"JohnSmith"}' Copyright (c) 2023 GUIORGY
El permiso se otorga, de forma gratuita, a cualquier persona que obtenga una copia de este software y archivos de documentación asociados (el "software"), para tratar en el software sin restricción, incluidos los derechos de los derechos de usar, copiar, modificar, fusionar, publicar, distribuir, sublicense y/o vender copias del software, y para permitir que las personas a quienes se les proporciona el software para hacer, sujeto a las siguientes condiciones: las siguientes condiciones: las siguientes condiciones: las siguientes condiciones:
El aviso de derechos de autor anterior y este aviso de permiso se incluirán en todas las copias o porciones sustanciales del software.
El software se proporciona "tal cual", sin garantía de ningún tipo, expresa o implícita, incluidas, entre otros, las garantías de comerciabilidad, idoneidad para un propósito particular y no infracción. En ningún caso los autores o titulares de derechos de autor serán responsables de cualquier reclamo, daños u otra responsabilidad, ya sea en una acción de contrato, agravio o de otra manera, que surge, de o en relación con el software o el uso u otros tratos en el software.