Copyright ©

Mongoose OS Forum

ATTENTION! This forum has moved to:

Do not post any new messages.

Converting c++ structure array to JSON

vsoralvsoral Australia
edited October 2018 in Mongoose OS

I am new to this forum, so perhaps this question has been asked before.

I am using JSON (frozen) library where I need to send an array of c++ structure as a JSON string from my c++ Server to a web client application.

Are there any sample code snippets that can guide me on the usage of library to achieve this?

My c++ structure is as below:

     int l, r, s;

The server application generates an array of sCPP elements, that I need to to convert to JSON string before sending to my web client.
Not very clear from the documentation.

Some example code snippets may be helpful.



  • mamuespmamuesp Germany/Northern coast

    Perhaps this part of the documentation might help. Its a good start.

  • struct sCPP { int l, r, s; }; static int print_sCPP(struct json_out *out, va_list *ap) { const struct sCPP *p = va_arg(*ap, const struct sCPP *); return json_printf(out, "{l: %d, r: %d, s: %d}", p->l, p->r, p->s); } enum mgos_app_init_result mgos_app_init(void) { struct sCPP data[3]; for (size_t i = 0; i < (sizeof(data) / sizeof(data[0])); ++i) { data[i].l = i; data[i].r = i + 1; data[i].s = i + 2; } struct mbuf jsmb; struct json_out jsout = JSON_OUT_MBUF(&jsmb); mbuf_init(&jsmb, 0); json_printf(&jsout, "{data: ["); for (size_t i = 0; i < (sizeof(data) / sizeof(data[0])); ++i) { json_printf(&jsout, (0==i)?"%M":", %M", print_sCPP, data+i); } json_printf(&jsout, "]}"); LOG(LL_INFO, ("%.*s", jsmb.len, jsmb.buf)); mbuf_free(&jsmb); return MGOS_APP_INIT_SUCCESS; }


    mgos_app_init        {"data": [{"l": 0, "r": 1, "s": 2}, {"l": 1, "r": 2, "s": 3}, {"l": 2, "r": 3, "s": 4}]}
Sign In or Register to comment.