elnormous / HTTPRequest

Single-header C++ HTTP request class
The Unlicense
942 stars 213 forks source link

add Json #38

Closed mathio3 closed 3 years ago

mathio3 commented 3 years ago

add simple json handler if need to post Json

using namespace std;

namespace R2 {

class Json {
public:

    string serialize(map<string, string> data)
    {
        string _d;

        _d = "{";

        map<string, string>::iterator it;

        for (it = data.begin(); it != data.end(); ++it)
        {
            if (it == prev(data.end()))
            {
                _d += "\"" + it->first + "\": \"" + it->second + "\"}";
                break;
            }

            _d += "\"" + it->first + "\": \"" + it->second + "\", ";
        }

        return _d;
    }

};}

USING :

R2::Json json; 
string data = json.serialize(map<string, string>({{"username", "mathio"},{"password", "MyPass"}}));
elnormous commented 3 years ago

You should use a JSON library like https://github.com/nlohmann/json for JSON encoding. JSON is not a part of the HTTP standard (RFC 7231) so it is out of the scope of this library. I added an example on hot wo send a JSON POST in https://github.com/elnormous/HTTPRequest/commit/b6b87953e5a639ba6c88e574c6d972a728463da8.