Search code examples
c#mysqljsonlistvarchar

Read MySQL JSON datatype and cast it into List<Int> in C#


I am trying to return a list of numbers from mysql database which has JSON datatype in the table.

the mysql.connector in c# thinks the datatype is VARCHAR so basically I get in return "[1, 2, 3]" from the database.

I need to cast the string return into List<INT> so I can work with it directly.

to be more specific, that's what I get from the mysql reader

string mylist = "[1, 2, 3]"

and I want to cast it into

List<Int> mylist_int = [1, 2, 3]

So if there is a way to read JSON datatype from the database directly in JSON format that would be great.

alternatively I am looking for a way to parse the string list and convert it into c# native list.

Thank you,


Solution

  • Use a JSON parser like JSON.NET to parse the JSON string, eg :

    var json=reader.GetString(0);
    //Returns a List<int>
    var myList=JsonConvert.DeserializeObject<List<int>>(json);
    

    or

    var jsonArray=JArray.Parse(json);
    

    MySQL Connector explicitly treats JSON as a string, it doesn't "think" they are text :

        case MySqlDbType.Set:
        case MySqlDbType.Enum:
        case MySqlDbType.String:
        case MySqlDbType.VarString:
        case MySqlDbType.VarChar:
        case MySqlDbType.Text:
        case MySqlDbType.TinyText:
        case MySqlDbType.MediumText:
        case MySqlDbType.LongText:
        case MySqlDbType.JSON:
        case (MySqlDbType)Field_Type.NULL:
          return new MySqlString(type, true);
    

    The library's own tests use GetString() to read JSON data :

    [Fact]
    public void CanReadJsonValue()
    {
      ...
      using (MySqlDataReader reader = cmd.ExecuteReader())
      {
        Assert.True(reader.Read());
        Assert.Equal("[\"a\", {\"b\": [true, false]}, [10, 20]]", reader.GetString(0));
      }    
    }