6

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

1 Answer 1

14

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.