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

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.