Does this look familiar?
\"Action\":\"Upload\",
\"FromVersion\":\"ver1\",
\"ToVersion\":\"ver2\"
Wouldn't it be awesome to be able to write like this instead?
"Action":"Upload",
"FromVersion":"ver1",
"ToVersion":"ver2"
Escape characters exists for a simple reason. It says "do not interpret the character after as it should be interpreted". But if we are writing Json we should put escape character way too often. The resulting string could be unreadable. But a simple solution exists:
...
Done! That simple. Here we use a technique called stringification. It accepts a variadic macro, variable number of arguments, in other words. And it stringifies them! Meaning it produces strings. So all the parameters are stringified and then concatenated separately, because two string in C are always concatenated if put next to each other, i.e.
will produce "foobar". Note, that I'm talking about strings here, not the pointers to array of chars or string objects from C++. No, pure strings, such as "I'm a string".
This technique should work on all modern compilers. Was tested on GCC, Clang, MS compiler.
\"Action\":\"Upload\",
\"FromVersion\":\"ver1\",
\"ToVersion\":\"ver2\"
"Action":"Upload",
"FromVersion":"ver1",
"ToVersion":"ver2"
Escape characters exists for a simple reason. It says "do not interpret the character after as it should be interpreted". But if we are writing Json we should put escape character way too often. The resulting string could be unreadable. But a simple solution exists:
- #define MAKE_STRING(...) #__VA_ARGS__
...
- const char *json(MAKE_STRING( {
- "Action":"Upload",
- "FromVersion":"ver1",
- "ToVersion":"ver2" } );
Done! That simple. Here we use a technique called stringification. It accepts a variadic macro, variable number of arguments, in other words. And it stringifies them! Meaning it produces strings. So all the parameters are stringified and then concatenated separately, because two string in C are always concatenated if put next to each other, i.e.
- "foo" "bar"
will produce "foobar". Note, that I'm talking about strings here, not the pointers to array of chars or string objects from C++. No, pure strings, such as "I'm a string".
This technique should work on all modern compilers. Was tested on GCC, Clang, MS compiler.
No comments:
Post a Comment