chwarr chwarr - 1 month ago 14
JSON Question

Why is the JSON serialization of a Bond map an array instead of a dictionary?

Say I have a Bond struct like

struct Person
{
0: string name;
1: map<string, string> phone_numbers;
}


When I serialize an instance of this object to JSON using
SimpleJsonWriter
, I get the following

{"name":"Jenny","phone_numbers":["home","867-5309","office","555-1212"]}


Notice that
phone_numbers
is an array of strings.

But I would expect something more like this:

{"name":"Jenny","phone_numbers":{"home":"867-5309","office":"555-1212"}}


where
phone_numbers
is an object with two members.

What's going on?

Answer

Bond's Simple JSON protocol uses valid JSON, but it isn't always the most idiomatic JSON. The best way to parse Bond's Simple JSON protocol is to use Bond itself.

In this particular case, we need to remember that Bond allows map with keys of other primitive types (e.g. integers, doubles, bools). So, Bond uses an array of key+value pairs for all maps.

For example, a map<int32, string> is serialized as

"numbers":[1,"unu",2,"du",3,"tri"]

The C# objects that gbc generates for C# are very simple. Newtonsoft's Json.NET library can often serialize them to more idiomatic JSON without any problems. Bond uses this library to implement some of its JSON support, so this won't be a new dependency for you either, if you need to has idiomatic JSON output.

For C++, you could write a custom transform to use a JSON serialization library of your choice if you needed idiomatic JSON output.

Conceivably, map<string, string> could be special-cased to serialize to an object. Also, conversion rules to encode/decode all the primitives types to a member name could be used.

However, such a change to the existing Simple JSON protocol would break existing serialized data, which is not something you want from a serialization library. :-)

A change like this would need to be added in either a new version of simple JSON or as a new JSON serialization protocol with--perhaps--limited compatibility with the existing Simple JSON protocol.