skip to Main Content

I receive dynamic JSON in my web api post request.

[HttpPost("receive")]
public async Task<IActionResult> ReceiveJson([FromBody] JsonDocument document)

One of my JSON elements is a binary array:

"attachments": [
    {
        "content": [
            255,
            216,                
            ...
            128,
            70
        ]
    }

I am unable to read that array into anything really.
I can get it as a JsonElement and see that it is ValueKind Array:

ok = attachment.TryGetProperty("content", out JsonElement attachmentContent);
string attachmentContentType = attachmentContent.ValueKind.ToString();
//gives Array

But how do I get it itto a byte[]?

2

Answers


  1. The following code is a custom JSON converter for byte array:

    public class JsonByteArrayConverter : JsonConverter<byte[]>
    {
        public override byte[] Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
        {
            if (reader.TokenType != JsonTokenType.StartArray)
            {
                throw new JsonException();
            }
    
            var byteArray = new List<byte>();
            while (reader.Read())
            {
                if (reader.TokenType == JsonTokenType.EndArray)
                {
                    return byteArray.ToArray();
                }
    
                if (reader.TokenType == JsonTokenType.Number)
                {
                    byteArray.Add(reader.GetByte());
                }
            }
    
            throw new JsonException();
        }
    
        public override void Write(Utf8JsonWriter writer, byte[] value, JsonSerializerOptions options)
        {
            throw new NotImplementedException();
        }
    }
    

    As an example:

    string jsonString = "{"attachments":[{"content":[255,216,12,70]}]}";
    
    // Deserialize the JSON string
    var deserializedObject = JsonConvert.DeserializeObject<dynamic>(jsonString);
    
    // Access the binary array and convert it to a byte array
    byte[] byteArray = deserializedObject.attachments[0].content.ToObject<byte[]>();
    
    Login or Signup to reply.
  2. Following code retrieves byte[] from the JsonElement:

    int count;
    List<byte> contentValues = new List<byte>();
    
    using (JsonDocument document = JsonDocument.Parse(jsonString))
    {
        JsonElement root = document.RootElement;
        JsonElement attachmentsElement = root.GetProperty("attachments");
    
        count = attachmentsElement.GetArrayLength();
    
        foreach (JsonElement student in attachmentsElement.EnumerateArray())
        {
            if (student.TryGetProperty("content", out JsonElement contentElement))
            {
                foreach(JsonElement ele in contentElement.EnumerateArray())
                {
                    contentValues.Add(ele.GetByte());
                }
            }
        }
    }
    
    byte[] allContents = contentValues.ToArray();
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search