Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to map MySQL JSON column using Dapper

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#.

like image 907
Sibtain Norain Avatar asked Dec 24 '22 13:12

Sibtain Norain


1 Answers

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.

like image 185
Darren Clark Avatar answered Jan 04 '23 07:01

Darren Clark