Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Parse byte array to json with Json.Net

Tags:

json

c#

I'm trying to parse byte[] array to Dictionary<String,Object> using Json.Net but with no success

Actually I'm in doubt about its possibility. So is it possible? with this library or with anyother library?

here is what I have tried but DeserializeObject excepts only string as parameter afaik

public static Dictionary<String, Object> parse(byte[] json){
     Dictionary<String, Object> values = JsonConvert.DeserializeObject<Dictionary<String, Object>>(json);
     return values;
}
like image 955
Ismail Sahin Avatar asked Dec 24 '13 18:12

Ismail Sahin


People also ask

Can I put a byte array in JSON?

JSON does not support that. Use Base64. That is your library supporting it, not JSON itself. The byte array wont be stored as byte array in the JSON, JSON is a text format meant to be human readable.

Can you convert bytes to JSON?

Once you have the bytes as a string, you can use the JSON. dumps method to convert the string object to JSON.

How is byte represented in JSON?

The char type in Universal Binary JSON is an unsigned byte meant to represent a single printable ASCII character (decimal values 0-127). Put another way, the char type represents a single-byte UTF-8 encoded character.

What is System Text JSON?

Text. Json. Serialization namespace, which contains attributes and APIs for advanced scenarios and customization specific to serialization and deserialization.


2 Answers

Is the byte[] some sort of encoded text? If so, decode it first, e.g. if the encoding is UTF8:

public static Dictionary<String, Object> parse(byte[] json){
     string jsonStr = Encoding.UTF8.GetString(json);
     return JsonConvert.DeserializeObject<Dictionary<String, Object>>(jsonStr);
}
like image 163
Tim S. Avatar answered Oct 08 '22 13:10

Tim S.


To understand what's in the byte[] you should specify the encoding and use an method that could actually get byte[].

As I'm not aware of such method this will be the solution for your problem -

So the correct way to do it will be -

public static Dictionary<String, Object> parse(byte[] json)
{
    var reader = new StreamReader(new MemoryStream(json), Encoding.Default);

    Dictionary<String, Object> values = new JsonSerializer().Deserialize<Dictionary<string, object>>(new JsonTextReader(reader));

    return values;
}

Another way that might help explain what was should be done to deserilaize will be -

var jsonString = System.Text.Encoding.Default.GetString(json);
            Dictionary<String, Object> values = JsonConvert.DeserializeObject<Dictionary<String, Object>>(jsonString);
like image 28
Maxim Avatar answered Oct 08 '22 11:10

Maxim