jorgen / json_struct

json_struct is a single header only C++ library for parsing JSON directly to C++ structs and vice versa
Other
422 stars 57 forks source link

Serializer::writeAsString will not write empty string #11

Closed karlstav closed 3 years ago

karlstav commented 3 years ago

the Serializer::writeAsString will write nothing when given "" as data, most likely resulting in a bad JSON.

to reproduce give it something like ... {"key1": "value1", "key2" : "", "key3":"value3"}... the output will be:

 {
    "key1": "value1",
    "key2": ,
    "key3": "value3"
 }

the problem might be in the tokenizer giving the token size = 0.

or is the code wrong?

std::string prettify(const std::string& json) const
{
    std::string prettyJson;

    JS::Tokenizer tokenizer;
    tokenizer.addData(json.c_str(), json.size());
    JS::Token token;
    JS::Error e = JS::Error::NoError;
    JS::JsonTokens jsonTokens;

    while (e == JS::Error::NoError)
    {
        e = tokenizer.nextToken(token);
        if (e == JS::Error::NoError)
            jsonTokens.data.emplace_back(token);
    }
    assert(e == JS::Error::NeedMoreData);

    JS::SerializerContext context(prettyJson);
    context.serialize(jsonTokens.data);

    return prettyJson;
}
jorgen commented 3 years ago

fixed by d7601687598e7639278917db1038c2e8567d3ebd