I have a table in MySQL database which contains a JSON data type column. Is it possible to retrieve the JSON data stored in that column and map to my c# class using Dapper? Below is a sample JSON about how data is stored in column.
[
{
"ServerName": "",
"Priority": 1,
"FilesystemBasePath": "",
"IsAvailable": 1,
"ApplicationDocumentType": ""
},
{
"ServerName": "",
"Priority": 2,
"FilesystemBasePath": "",
"IsAvailable": 1,
"ApplicationDocumentType": ""
}
]
I want the data to be mapped to a List<MyObject>
type in C#.
You register an ITypeHandler for List<MyObject>
, or whatever the property type is.
public class MyClass
{
public List<MyObject> MyObjects {get; set; }
}
public class JsonTypeHandler: SqlMapper.ITypeHandler
{
public void SetValue(IDbDataParameter parameter, object value)
{
parameter.Value = JsonConvert.SerializeObject(value);
}
public object Parse(Type destinationType, object value)
{
return JsonConvert.DeserializeObject(value as string, destinationType);
}
}
SqlMapper.AddTypeHandler(typeof(List<MyObject>),new JsonTypeHandler());
After that if you have a column name that maps to a property of type List<MyObject>
it will be serialized and deserialized properly.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With