Keval Shukla
Keval Shukla

Reputation: 447

How to convert a binary string to json string in flutter

I am working with angel broking socket connection in flutter where I am fetching the stocks data using socket. In return, I am getting a binary compressed string which I need to convert into json string. Angel broking java sdk has provided that conversion in java but I want to know how do I convert the same in dart. Here I am sharing the java code for reference which I need to use in dart.

 String data = "eJyLrlZKzFayUsrLVtJRKkksBrGT84Ds3OJ0CLM2FgDCiAqQ"; // I am getting this string from socket

            byte[] decoded = Base64.getDecoder().decode(data);
            byte[] result = decompress(decoded);
            String str = new String(result, StandardCharsets.UTF_8);

            JSONArray tickerData = new JSONArray(str);

 public static byte[] decompress(byte[] compressedTxt) throws IOException {
    ByteArrayOutputStream os = new ByteArrayOutputStream();
    try (OutputStream ios = new InflaterOutputStream(os)) {
        ios.write(compressedTxt);
    }

    return os.toByteArray();
}

Please help me to convert this java code into flutter dart.

Upvotes: 0

Views: 1176

Answers (1)

pskink
pskink

Reputation: 24720

the following code:

final str = 'eJyLrlZKzFayUsrLVtJRKkksBrGT84Ds3OJ0CLM2FgDCiAqQ';
print(utf8.fuse(zlib).fuse(base64).decode(str));

prints [{"ak":"nk","task":"cn","msg":"cn"}]

EDIT but if the only thing you want to do with that decoded string is to call json.decode method then you can go one step further:

List l = json.fuse(utf8).fuse(zlib).fuse(base64).decode(str));
print(l);
print(l[0]);
print(l[0]['task']);

Upvotes: 3

Related Questions