简体   繁体   中英

Blob and JSON: How to encode and decode

Dart's JSON.encode and JSON.decode doesn't work with BLOB SQL type. I was searching for a solution and found a lot of explanations on why it doesn't work out of the box (or natively).

So I would like to know how can I encode and decode BLOB data with JSON efficiently.

EDIT 1: Adding an example.

I have a TEXT type field called "some_text" on a MySQL database. Here follows its content: "This is some_text field content".

When SQLJocky returns some_text, it is stored in Dart on a var as "Blob". A simple "returnVar.runtimeType" confirms it.

So now I need to "convert" this Blob text to a normal String, as JSON.encode/decode doesn't work with the first.

this should work, not tested though

import 'package:crypto/crypto.dart';

var base64String = CryptoUtils.bytesToBase64(yourBlob.toBytes());

the other direction

var blob = new Blob.fromBytes(CryptoUtils.base64StringToBytes(base64String));

The question is rather old but maybe this can still be useful to someone.

I also needed to extract string from a field returned as Blob by sqljocky and I found from the source code that Blob has two methods to extract data ' toString() ' and ' toBytes() '. So in order to encode the sqljocky row containing Blob data and extracting it as string, the code will look like this:

import 'dart:convert';
import 'package:sqljocky5/sqljocky.dart';
...
var rowText = json.encode(row, toEncodable: (dynamic item) {
    if (item is Blob) {
        return item.toString();
    }
    return item;
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM