JsonExtensions
1.0.0
.NET System.text.json을위한 확장자 모음
단일 JSON 객체와 JSON 배열을 모두 C# 배열로 삼키는 JSONCONVERTER.
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" jsonPropertyNames 속성 및 JSONMULTINAMEMODIFIER는 여러 JSON 키를 하나의 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"}' 저작권 (C) 2023 Guiorgy
이에 따라이 소프트웨어 및 관련 문서 파일 ( "소프트웨어")의 사본을 얻는 사람에게는 허가가 부여됩니다. 소프트웨어의 사용, 복사, 수정, 합병, 배포, 배포, 숭고 및/또는 소프트웨어의 사본을 판매 할 권한을 포함하여 제한없이 소프트웨어를 처리 할 수 있도록 소프트웨어를 제공 할 권한이 없습니다.
위의 저작권 통지 및이 권한 통지는 소프트웨어의 모든 사본 또는 실질적인 부분에 포함되어야합니다.
이 소프트웨어는 상업성, 특정 목적에 대한 적합성 및 비 침해에 대한 보증을 포함하여 명시 적 또는 묵시적 보증없이 "그대로"제공됩니다. 어떠한 경우에도 저자 또는 저작권 보유자는 계약, 불법 행위 또는 기타, 소프트웨어 또는 소프트웨어의 사용 또는 기타 거래에서 발생하는 계약, 불법 행위 또는 기타의 행동에 관계없이 청구, 손해 또는 기타 책임에 대해 책임을지지 않습니다.