mtrempoltsev / pods

Fast and simple C++ serializer
MIT License
33 stars 2 forks source link

JSON in different order can not be deserialized #19

Open Sagalo04 opened 1 week ago

Sagalo04 commented 1 week ago

Description

I am working on a http server which is receiving JSON data, but this data must be deserialized into a struct, if I am sending the JSON object in the same order as the struct it will be deseriealized, however if I send the data in a different order which is a common JSON behavior through different frameworks and clients it will throw a pods error.

To Reproduce

This is a quick implementation of the server using pods to handle the JSON Request

/*...*/
struct strctJSONopt
{
    std::string name;
    std::string value;

    PODS_SERIALIZABLE
    (
        PODS_OPT(name),
        PODS_OPT(value)
    )
};

struct strctJSON
{
    std::string url;
    std::string image;
    std::vector<strctJSONopt> options;

    PODS_SERIALIZABLE(
        PODS_MDR(url),
        PODS_OPT(image),
        PODS_OPT(options)
    )
};

struct strctJSONContainer
{
    strctJSON Data;

    PODS_SERIALIZABLE
    (
        PODS_MDR(Data)
    )
};

/*...*/

httplib::Server svr;
svr.Post("/ENDPOINT", [](const httplib::Request &req, httplib::Response &res) {
    std::string sBody = req.body
    std::stringstream ss;
    ss<< sBody ;

    strctJSONContainer loaded;
    pods::InputStream in(ss);
    pods::JsonDeserializer<decltype(in)> deserializer(in);
    if (deserializer.load(loaded) != pods::Error::NoError)
    {
        std::cerr << "deserialization error\n";
        res.set_content("{\"Error\":\"deserialization error\"}","application/json")
    }

    /*...*/

});

This is how the JSON must be to work

{
    "Data": {
        "url": "localhost:3000/endpoint",
        "image": "base64image",
        "options": [{"name": "isPNG", "value": "true"},{"name": "compression", "value": "0.9"}]
    }
}

but is the order change it doesn`t work, for example like this JSON:

{
    "Data": {
        "image": "base64image",
        "url": "localhost:3000/endpoint",
        "options": [{"name": "isPNG", "value": "true"},{"name": "compression", "value": "0.9"}]
    }
}

It is also have some problems with JSON such the following one:

{
    "Data": {
        "url": "localhost:3000/endpoint",
        "image": "base64image",
        "options": null  //The issue comes here or in any null value in optional fields
    }
}
mtrempoltsev commented 1 week ago

Hi Santiago, The fact that the order of fields in the JSON has matters is a limitation of JSON SAX parser. This limitation is made to improve performance.