34

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;
}
3
  • do you want to serialize it? Commented Dec 24, 2013 at 18:22
  • What is this byte[] data's format? E.g. is it encoded JSON text? Commented Dec 24, 2013 at 18:23
  • yes Pouya Samie, I want to serialize and yes Tim S. its encoded as json format Commented Dec 24, 2013 at 18:25

2 Answers 2

50

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);
}
Sign up to request clarification or add additional context in comments.

Comments

6

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);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.