Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can dapper deserialize json stored as text?

Tags:

json

c#

dapper

public class MyType
{
    public int Id { get; set;}
    public int[] MyArray { get; set; }
}

var sql = "SELECT id, MyArrayAsJson as MyArray";
var x = await connection.QueryAsync<MyType>(sql);

I have a string stored in the database which looks like json: [1,2,3,4,5]

When I query the db with Dapper, I would like dapper to deserialize to an object, MyType. Dapper wants MyArrayAsJson to be a string because it is, but I want it to deserialize to an int array. Is this possible?

like image 647
Joe Phillips Avatar asked Jan 03 '23 12:01

Joe Phillips


1 Answers

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(int[]), new JsonTypeHandler());
like image 92
Palindromer Avatar answered Jan 05 '23 18:01

Palindromer