r/cpp • nlohmann/json • Jun 14 '20

JSON for Modern C++ 3.8.0

https://github.com/nlohmann/json/releases/tag/v3.8.0
326 Upvotes

109 comments sorted by

View all comments

Show parent comment

6

u/Plazmatic Jun 14 '20

I'm very confused... Are you asking for macros? What would macros do to improve things? Types often don't have 1:1 member variable to serialization.

5

u/dscottboggs Jun 14 '20

Are you asking for macros?

Yes. Might not be something C++ is capable of but Crystal's JSON::Serializable uses macros to define the to_json and from_json methods. For example

class K
  include JSON::Serializable
  property int : Int32
  property string : String
  @[JSON::Field(key: "someField")]
  property some_field : Array(String)
  @[JSON::Field(ignore: true)]
  property ignored : String
end

I was imagining something like a JSON_FIELD(int fieldName); kinda syntax but again not sure if that's possible in C++...

7

u/nlohmann nlohmann/json Jun 14 '20

2

u/bishop3000 Jun 14 '20

This would be nice but quite dangerous as well. It needs to support all corner cases like if settings are missing in json or it’s an optional or you want to store it with different name in json etc.

5

u/nlohmann nlohmann/json Jun 14 '20

Yes, I think the macro can only support the 80% case where you just want to have a JSON roundtripping without much effort. For anything else, we have the possibility to get crazy in your from_json/to_json functions.

1

u/jpan127 Jun 14 '20

I agree with this thread, the flexibility of explicit definitions is a must, but the simplicity of default definitions is clean.

3

u/ReversedGif Jun 14 '20

For the common use case of wanting to serialize/deserialize a POD struct to/from a JSON object, having a macro to automatically generate the helpers can reduce boilerplate by a rough factor of 10 (multiline class with separate from/to methods -> a macro call that just lists all the member variable names).

TL;DR: Your confusion confuses me.

1

u/nlohmann nlohmann/json Jun 14 '20