Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert JSON Bytes in Javascript

I have inherited a somewhat large, Java- based server- side codebase that communicates with clients using JSON. For several reasons, the Jackson- based JSON conversions must use the binary form -- in other words, the JSON that I am generating on the server side is made up of bytes, not characters.

This was not a problem with previous clients, because they were all Java based. I could use the Jackson libraries to convert the binary back into objects. Unfortunately, I have been asked to create some browser- based clients that require the use of Javascript in order to receive and display the JSON information.

I am attempting to use JQuery's JSON conversion functions, but it turns out that neither JQuery nor the regular Javascript functions are capable of converting a set of JSON bytes back into an object. I need to convert the bytes back into characters in order to convert them back into objects.

I learned that in order to convert bytes into characters, I have to get the bytes into a byte array. This is where I am having the problems.

I have been trying to use various methods to convert the binary JSON information back into a form (a byte array) that can be converted into a meaningful object using the JSON conversion functions. I have tried using the ArrayBuffer to convert the data into a byte buffer, then the int8Array() function to create a byte array:

var buffer = new ArrayBuffer(obj.payload.length);
var bits =  new Int8Array(buffer);

I also attempted to use uint8Array(), and tried various other conversion routines found on the Internet (and here in Stack Overflow) in order to create the array that can be converted into meaningful characters. All my attempts have either caused errors and failures at runtime, or have generated garbage that breaks the JSON converters.

Is there some way to get Javascript to read a set of bytes generated by Jackson so that they can be converted back to objects using the JSON converters? Or is Javascript only capable of converting JSON strings?

Someone please advise...

like image 270
Factor Three Avatar asked Apr 17 '26 21:04

Factor Three


1 Answers

Assume your binary JSON is something like this:

[123, 34, 107, 101, 121, 34, 58, 34, 118, 97, 108, 117, 101, 34, 125]

you could easily convert it to a string:

var str = String.fromCharCode.apply(String, data);

and parse that with the JSON objects parse:

JSON.parse(str);

jsfiddle

like image 71
Imperative Avatar answered Apr 19 '26 10:04

Imperative



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!