개발/C#
Generic 타입(T)를 이용해 String과 JSON오브젝트 간 상호 변환하는 함수
다물칸
2024. 5. 27. 15:11
728x90
반응형
Generic 타입(T)를 이용해 String과 JSON오브젝트를 상호 변환하는 함수입니다.
범용적으로 사용할 수 있어요.
options는 JSON의 규칙을 설정할 수 있습니다.
상세 옵션은 여기에서 확인해주세요.
using Newtonsoft.Json;
private static string JsonObjToString<T>(T obj)
{
try
{
if (obj == null) return "";
var options = new JsonSerializerSettings
{
MetadataPropertyHandling = MetadataPropertyHandling.Ignore,
DateFormatString = "yyyy-MM-dd HH:mm:ss",
Formatting = Formatting.Indented,
NullValueHandling = NullValueHandling.Ignore,
};
string strJson = JsonConvert.SerializeObject(obj, options);
return strJson;
}
catch (Exception ex)
{
return default;
}
}
private static T StrToJsonObj<T>(string strJson)
{
try
{
if (String.IsNullOrEmpty(strJson)) return default;
var options = new JsonSerializerSettings
{
MetadataPropertyHandling = MetadataPropertyHandling.Ignore,
DateFormatString = "yyyy-MM-dd HH:mm:ss",
Formatting = Formatting.Indented,
NullValueHandling = NullValueHandling.Ignore,
};
T Obj = JsonConvert.DeserializeObject<T>(strJson, options);
return Obj;
}
catch (Exception ex)
{
return default;
}
}
반응형