msgpack-c icon indicating copy to clipboard operation
msgpack-c copied to clipboard

How to pack raw json?

Open xiaoxiangdu opened this issue 11 years ago • 5 comments

Hi guy,

I want to convert raw json to msgpack object. For example: I have json string: {"quest":"one", "int":2, "double":3.3, "boolean":true} How can I do it?

Thanks. Mack

xiaoxiangdu avatar Jan 20 '15 09:01 xiaoxiangdu

Unfortunately, msgpack-c doesn't support conversion from json to msgpack::object directly. You need to use a json parser like https://github.com/kazuho/picojson .

redboltz avatar Jan 20 '15 10:01 redboltz

Yes, but after parse it to json object use s json parser, How can I convert json object to msgpack object?

xiaoxiangdu avatar Jan 20 '15 11:01 xiaoxiangdu

There are some ways to do that. For example, create a msgpack format from json string. Then unpack msgpack::object from created format:

#include <msgpack.hpp>
#include <sstream>
#include <iostream>

// {"quest":"one", "int":2, "double":3.3, "boolean":true}

int main() {
    std::stringstream ss;
    {
        msgpack::packer<std::stringstream> pk(ss);

        pk.pack_map(4);

        pk.pack("quest");
        pk.pack("one");

        pk.pack("int");
        pk.pack(2);

        pk.pack("double");
        pk.pack(3.3);

        pk.pack("boolean");
        pk.pack(true);
    }
    {
        msgpack::unpacked ud = msgpack::unpack(ss.str().data(), ss.str().size());
        msgpack::object const& obj = ud.get();
        std::cout << obj << std::endl;
    }
}

redboltz avatar Jan 20 '15 14:01 redboltz

Yes, I know this way. But in my application, I first get a json string, such as {"quest":"one", "int":2, "double":3.3, "boolean":true}, and sometime I do not know the content of json string, so I need parse it to a json object use rappidjson etc, But after I parse it to json object, I want to convert it to msgpack object? Do there any way to do this?

xiaoxiangdu avatar Jan 21 '15 01:01 xiaoxiangdu

done, I write a function to parse rapidjson object to msgpack object.

xiaoxiangdu avatar Jan 21 '15 09:01 xiaoxiangdu