Is it possible to parse from a stringstream without throwing ? #2597
-
I am receiving multiple JSONs on a tcp socket, here is my current implementation: (This is in a method called each time the fd is read-ready) char buff[WORKER_BUF_SZ];
int ret = ::read(fd, buff, WORKER_BUF_SZ);
rBuffer.write(buff, ret);
auto pos = rBuffer.tellg();
bool isJson = json::accept(rBuffer);
rBuffer.seekg(pos, rBuffer.beg);
if (isJson) {
json j;
j << rBuffer;
onJson(srv, std::move(j));
} This could be greatly simplified by using operator<< without throwing char buff[WORKER_BUF_SZ];
int ret = ::read(fd, buff, WORKER_BUF_SZ);
rBuffer.write(buff, ret);
json j;
j << json::settrhow(false) << rBuffer;
if (!j.is_discarded()) {
onJson(srv, std::move(j));
}
// Maybe seek the stream back if the parser doesn't do it Alternatively, if I could know of many bytes json::parse() or accept() consumed, I could maintain a char array myself and discard the x first bytes after parsing. Thank you for reading through. |
Beta Was this translation helpful? Give feedback.
Replies: 3 comments 3 replies
-
Did you have a look at https://json.nlohmann.me/features/parsing/parse_exceptions/? |
Beta Was this translation helpful? Give feedback.
-
Yes, and I does not provide a way to disable exceptions through operator<<, only through json::parse, which I can't use because the parser is called in strict mode and I may have several jsons in the buffer. I can't throw because I may receive the json byte by byte, and if I throw each time it's going to take forever. I'd like to call the parser this way: detail::parser<basic_json>(input_adapter(i), nullptr, false).parse(false, result); json::parse will not allow me to do so (strict is hard coded to true), so I'm calling the parser myself: void Worker::onReadReady(Server& srv) {
char buff[WORKER_BUF_SZ];
int ret = read(fd, buff, WORKER_BUF_SZ);
rBuffer.write(buff, ret);
json j;
nlohmann::detail::parser<nlohmann::basic_json<>>(nlohmann::detail::input_adapter(rBuffer), nullptr, false).parse(false, j);
if (!j.is_discarded()) {
onJson(srv, std::move(j));
}
} 1 - Is there a better way ? Thanks ! |
Beta Was this translation helpful? Give feedback.
-
Resolved: #2597 (reply in thread) |
Beta Was this translation helpful? Give feedback.
Resolved: #2597 (reply in thread)