| name | enforcing-json-options-predefine |
| description | Force JsonSerializerOptions to be declared as static readonly or readonly fields instead of creating new instances inside methods. |
JsonSerializerOptions ์ฌ์ ์ ์ ๊ฐ์
์ค๋ช
JsonSerializerOptions๋ ์ฝ๊ธฐ ์ ์ฉ(ReadOnly) ๊ฐ์ฒด๋ก ์ค๊ณ๋์ด์ผ ํฉ๋๋ค. ๋ฉ์๋ ๋ด๋ถ์์ ๋งค๋ฒ ์๋ก ์์ฑํ๋ฉด ๋ถํ์ํ ๋ฉ๋ชจ๋ฆฌ ํ ๋น๊ณผ ์ฑ๋ฅ ์ ํ๊ฐ ๋ฐ์ํฉ๋๋ค.
JsonSerializerOptions๋ ๋ด๋ถ์ ์ผ๋ก ๋ฆฌํ๋ ์
์บ์๋ฅผ ์ ์งํ๋ฏ๋ก, ์ฌ์ฌ์ฉํ๋ฉด ์ง๋ ฌํ/์ญ์ง๋ ฌํ ์ฑ๋ฅ์ด ํฌ๊ฒ ํฅ์๋ฉ๋๋ค.
๊ท์น
JsonSerializerOptions๋ static readonly ํ๋ ๋๋ readonly ์ธ์คํด์ค ํ๋๋ก ์ฌ์ ์ ์ํฉ๋๋ค
- ๋ฉ์๋ ๋ด๋ถ์์
new JsonSerializerOptions { ... } ๋ฅผ ์ง์ ์์ฑํ์ง ์์ต๋๋ค
- ๋์ผํ ์ต์
๊ตฌ์ฑ์ด ์ฌ๋ฌ ๊ณณ์์ ์ฌ์ฉ๋๋ฉด ๊ณต์ ์์๋ก ์ถ์ถํฉ๋๋ค
Worst Case (๋์ ์)
public string GenerateJson(int count)
{
var data = GetData(count);
var jsonContent = JsonSerializer.Serialize(data, new JsonSerializerOptions
{
WriteIndented = true,
Encoder = JavaScriptEncoder.UnsafeRelaxedJsonEscaping
});
return jsonContent;
}
public async Task<T> Deserialize<T>(HttpResponseMessage response)
{
var json = await response.Content.ReadAsStringAsync();
return JsonSerializer.Deserialize<T>(json, new JsonSerializerOptions
{
PropertyNameCaseInsensitive = true
})!;
}
Best Case (์ข์ ์)
private static readonly JsonSerializerOptions JsonWriteOptions = new()
{
WriteIndented = true,
Encoder = JavaScriptEncoder.UnsafeRelaxedJsonEscaping
};
private static readonly JsonSerializerOptions JsonReadOptions = new()
{
PropertyNameCaseInsensitive = true
};
public string GenerateJson(int count)
{
var data = GetData(count);
return JsonSerializer.Serialize(data, JsonWriteOptions);
}
public async Task<T> Deserialize<T>(HttpResponseMessage response)
{
var json = await response.Content.ReadAsStringAsync();
return JsonSerializer.Deserialize<T>(json, JsonReadOptions)!;
}
์ ์ฉ ๋์
- ๋ชจ๋
JsonSerializer.Serialize() ํธ์ถ์์ ์ฌ์ฉํ๋ ์ต์
- ๋ชจ๋
JsonSerializer.Deserialize() ํธ์ถ์์ ์ฌ์ฉํ๋ ์ต์
- ํ
์คํธ ์ฝ๋์ JSON ์ง๋ ฌํ/์ญ์ง๋ ฌํ ์ต์
- ๋ฐ์ดํฐ ์์ฑ ๋๊ตฌ์ JSON ์ถ๋ ฅ ์ต์