Sprintf() and strings and JSON and webhook

Dear Community,
I’m not sure why, but the sprintf() function does not want to play with strings.
I’m trying to make a JSON object.

String strCurrTime;
strCurrTime = Time.format(Time.now(), "%Y-%m-%d %H:%M:%S");
sprintf(json,"{\"temperature\": \"%f\", \"location\": \"%s\",\"unixTime\": \"%s\"}",temperature,location,strCurrTime);

I get this somewhat annoying error:

error: cannot pass objects of non-trivially-copyable type ‘class String’ through ‘…’

I really don’t understand it; last time I hacked my way out of it by sticking my string into a const char array. But unfortunately this is not possible with my current task:

char strCurrTime[50]= Time.format(Time.now(), “%Y-%m-%d %H:%M:%S”);

does not work: > error: incompatible types in assignment of ‘String’ to ‘char [50]’

Is there a better way to include strings as data in a JSON object?
Thanks very much

You can use strCurrTime.c_str() as the parameter to sprintf, Serial.printlnf, etc.

3 Likes

Ha! That worked brilliantly! Thanks again @rickkas7, you’re a champ. :crown:

Some background here:
String is not the same as a char[] but a class (once instanciated an object) that helps you deal with strings.
But since printf() and its siblings expect a const char* at the position where a %s place holder has to be substituted it’s not happy to see the address of a String object which just happens to hold a char[] somewhere in its “belly”.
So you need a way to hand out that const char* printf() expects.
One way is as @rickkas7 said via a dedicated method (c_str()) or via the also available cast operator overload (my prefered solution :wink: )

Like this

String someString = "test";
printf("%s", (const char*)someString);
3 Likes

A really neat post @ScruffR. Thanks so much. Very well explained. I could not find this info in the Particle documentation examples - they don’t use strings. I have never used cast operator overload before, and when I saw code like this I could only really guess what it was doing, so this was really helpful to me.
Cheers and thanks
Lindsay

1 Like