2

I get a msgpack object, wrapping an array with uint8_t values from an API and load it to the nlohmann/json library with json::from_msgpack, when I print the json document I get this:

{
  "raw_data": {
    "bytes": [4, 3, 2, 0, 0, 116, 68],
    "subtype": null
  }
}

From the documentation I read that the default values for the BinaryType is std::vector<std::uint8_t>. But either way I try it, I get run-time errors like:

std::vector<uint8_t> unpack(std::vector<uint8_t> msg){
    json response_json = json::from_msgpack(msg);
    return response_json["raw_data"];
}
> terminate called after throwing an instance of 'nlohmann::detail::type_error'
>  what():  [json.exception.type_error.302] type must be array, but is binary
> Canceled

or

std::vector<uint8_t> unpack(std::vector<uint8_t> msg){
    json response_json = json::from_msgpack(msg);
    return response_json["raw_data"]["bytes"];
}

> terminate called after throwing an instance of 'nlohmann::detail::type_error'
> what():  [json.exception.type_error.305] cannot use operator[] with a string argument with binary
> Canceled

I also tried calling the set_subtype - since it is hinted, that the subtype of the binary is not set - but got the same error messages.

Copying the elements in an new vector would be an easy workaround, but I fell so close to accessing the existing vector, that this fells a little wrong. If anyone can give me a hint I would be very grateful :)

Paul Würtz
  • 1,641
  • 3
  • 22
  • 35
  • 2
    The library is not sure if you are requesting a list or binary data. `response_json["raw_data"].get_binary()` should get you out of that jam. –  Aug 09 '21 at 17:29
  • @Frank the binary representation could be 4bytes per value. I guess the target was getting a single byte per value. – tswaehn Aug 10 '21 at 07:28

0 Answers0