Search code examples
c++jsonpostnodemcuarduino-c++

JSON format in Arduino


I have a code that works fine if I input the values directly, but my current system is such that the values would have to change. see the code below.

char http_cmd[] =  "POST /tracker/ HTTP/1.1\r\nContent-Type: application/json\r\nContent-Length: 38\r\nHost: haul1.herokuapp.com\r\n\r\n{ \"trackerId\": \"2222\",\"height\": \"42\" }";

// this works fine

but I want to input the values as variables, so I did something like this

String tracker = "2222";
String height = "42";
char http_cmd[] =  "POST /tracker/ HTTP/1.1\r\nContent-Type: application/json\r\nContent-Length: 38\r\nHost: haul1.herokuapp.com\r\n\r\n{ \"trackerId\": \""+tracker+"\",\"height\": \""+height+"\" }"; 

this is the Error message I get

exit status 1
initializer fails to determine size of 'http_cmd'

Thank you as you attempt it. what I really need is an acceptable syntax of Json content type, I also need to know how to get the exact size of the "http_cmd"


Solution

  • There are actually two errors in your code. The error you see is because you create an char array without specify the length. There is another error that String concatenation with + is part of the Arduino String library, it is not part of c++ and therefore is not a valid operator for data type char.

    There are two ways to do it, 1) using String concatenation operator + from String library (all you need is to change your code from char http_cmd[] to String http_cmd); 2) using char array. But it is generally consider safer to use char array than String library. You can use sprintf() to create a string array, this works for all data type except for floating point in Arduino.

    For easy to calculate the length of the json payload and for readability, it is better to break the command into several strings. BTW, I assumed that the tracker and height are really int which can be encoded in JSON directly.

    int tracker = 2222;
    int height = 42;
    
    // create json payload
    char json[30];
    sprintf(json, "{\"trackerId\":%d,\"height\":%d}", tracker, height);
    
    char http_post_request[] = "POST /tracker/ HTTP/1.1\r\n";
    char http_content_type[] = "Content-Type: application/json\r\n";
    
    // calculate payload length
    char http_content_length[20];
    sprintf(http_content_length, "Content-Length:%lu\r\n", strlen(json));
    char http_host[] = "Host: haul1.herokuapp.com\r\n\r\n";