Skip to content

CBOR serialization of a given JSON value does not serialize #641

Closed

Description

@davidalbertonogueira

Hi,
I was CBOR serializing a JSON object, and noticed that, whereas when dumping a json object to a string, json string values (i.e., case value_t::string )are escaped (a call to escape_string is made), no such call is made when json values are string values in the CBOR approach.

I was reading the CBOR CRF 7049 and it seems that strings do not need to be escaped when serializing to CBOR.
From your library the behavior is consistent, you don't escape when serializing, nor except to be escaped when de-serializing.
But it appears that Newtonsoft.Json (C# library), expects that. Is it a valid expectation? Is it possible to have a serialization that behaves in this way, in case some libraries expect that behavior?

My use case involves reading the cbor byte string output in c#.
C++ side:

nlohmann::json json_doc;
json_doc["characters"] = nlohmann::json::array();
  
for (int i = 0; i < characters.size(); i++) {
  json_doc["characters"][i]["name"] = (characters[i] != nullptr) ? characters[i]->name() : "";
}

std::vector<uint8_t> cbor = nlohmann::json::to_cbor(json_doc);
output->assign((char*)&cbor[0], cbor.size());

C# side. cbor_bytes is the cbor byte string (c++ output vector)

CBORObject cbor = CBORObject.DecodeFromBytes(cbor_bytes);
output = cbor.ToString();

Such output string by then, is wrongly formed:
{"characters": [{"name": "Clara Oswald"}, {"name": "Kensi Blye"}, {"name": "Temperance "Bones" Brennan"}]}
and cannot, obviously be parsed:

JObject output_obj = JObject.Parse(output);

Activity

  1. nlohmann commented on Jun 28, 2017

    @nlohmann
    Owner

    I'm on holiday right now and cannot have a look at this issue for the next two weeks.

  2. CodeMasterYi commented on Jun 29, 2017

    @CodeMasterYi

    what about json_doc.dump()?

  3. davidalbertonogueira commented on Jun 29, 2017

    @davidalbertonogueira
    Author

    Already fixed it. It has nothing to do with nlohmann::json.
    In C#, the correct call is cbor.ToJSONString() instead of cbor.ToString(), as I was doing.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions