Search code examples
c#jsonjson.netjson-deserialization

Serialize Newtonsoft.Json.Linq.JObject in C# to byte[]


In C# application, I receive binary data at some point, which are serialized to JObject with structure

{
  "0": 255,
  "1": 216,
  "2": 255,
  "3": 224,
  "4": 0,
  "5": 16,
.
.
.
"12345" : 255

}

, so it's always {"index" : value}. EDIT: the json was just example, the JObject actually has 12345 children of type JToken, where each JToken has name "index" and value JValue (actual binary value).

I need to deserialize this JObject to byte[], with only values stored. Is there any smart way to do this, besides going through the object in cycle and storing the values in byte array, one by one?


Solution

  • The code you are looking for is :

    jObject.Properties().Select(p => (byte) p.Value).ToArray();
    

    But I still have 2 questions :

    1. Do you really need to convert it from binary to JSON ? Can't you directly deserialize it into an object ?

    2. It's clearly an array so why isn't your JSON an array like this :

      [ 255, 216, ... ]