How to convert string to char?

String testString = “{“token”:123456789,“barcode”:[123456789,987654321],“quantity”:[1,5]}”;

char *testChar;

testChar <<<< testString; ???

Because i want to use JSMN Library to Json parser
JSON parser for Spark
:smiley:

Check out this post (Are string variables fully supported? [SOLVED]) for some examples. For more info on the toCharArray() method see this link: https://www.arduino.cc/en/Reference/StringToCharArray

1 Like

Syntax

string.toCharArray(buf, len)

String testString = “{“token”:123456789,“barcode”:[123456789,987654321],“quantity”:[1,5]}”;

char *testChar;
testString.toCharArray(testChar, ?) how I know that I have to put that value. ?

What exactly do you want to do with your string?
If you just want work with it as const char* or pass it to a function that expects a const char*, you could use string.c_str().
If you want to copy the string into a char array, you can use string.toCharArray() together with string.length().
But you’d need a char[] big enough to take all your copied characters. char* does not allocate any RAM to store the string to.

But you could also look at the docs
https://docs.particle.io/reference/firmware/photon/#string-class

1 Like

I just want to clear up one point. When you do char *testChar; above, that does not allocate any storage for the array of characters, so the next line which does essentially a memcpy, will clobber whatever comes after that pointer in memory.

Do this instead:

String testString = "{\"token\":123456789,\"barcode\":[123456789,987654321],\"quantity\":[1,5]}";

char testChar[65];
testString.toCharArray(testChar, 65);
2 Likes

@bko, this can not be said often enough :wink:

2 Likes

Sorry I missed that in your response above! You were there before me again!

4 Likes

Thanks! This worked perfectly for converting the time returned in string format via Particles Time.timeStr() function to a char array to display on an LCD screen that requires the data in Char format.

2 Likes