Hi,
I want to parse and encode JSON data and send it over Bluetooth.
I couldn't find any proper example project.
I have the following struct and description:
struct sensor_data
{
float voc;
float co2;
bool is_fan_running;
bool is_lamps_on;
};
static const struct json_obj_descr sensor_data_descr[] = {
JSON_OBJ_DESCR_PRIM(struct sensor_data, voc, JSON_TOK_FLOAT),
JSON_OBJ_DESCR_PRIM(struct sensor_data, co2, JSON_TOK_FLOAT),
JSON_OBJ_DESCR_PRIM(struct sensor_data, is_fan_running, JSON_TOK_TRUE),
JSON_OBJ_DESCR_PRIM(struct sensor_data, is_lamps_on, JSON_TOK_TRUE),
};
I can parse it with the following code:
char json_msg[] = "{\"voc\":10.45,\"co2\":25.56,\"is_fan_running\":true,\"is_lamps_on\":false}";
struct sensor_data sensor_results;
ret = json_obj_parse(json_msg, sizeof(json_msg),
sensor_data_descr,
ARRAY_SIZE(sensor_data_descr),
&sensor_results);
But I cannot encode a struct to json:
char encoded_json[1024];
struct sensor_data sensor_results;
sensor_results.co2 = 45.0f;
sensor_results.voc = 21.0f;
sensor_results.is_fan_running = true;
sensor_results.is_lamps_on = true;
err = json_obj_encode_buf(sensor_data_descr, ARRAY_SIZE(sensor_data_descr), &sensor_results, encoded_json, 1024);
LOG_INF("Encode err: %d", err);
LOG_INF("Encode : %s", encoded_json);
It gives always:
[00:00:05.008,514] <inf> app: Encode err: -12
[00:00:05.008,544] <inf> app: Encode : {"voc":
How can I encode this struct to json string properly?
Thanks.