How to convert JSON String for example
{"f0":100,"f1":100,"f2":100}
It is what I get from my esp01 side from I2C communication
Now I want it to get it back to my Arduino side variables int f0 ,int f1 ,int f2
But example shown in web site uses kind of different serialized JSON
Example shown,
char json[] = "{\"sensor\":\"gps\",\"time\":1351824120,\"data\":[48.756080,2.302038]}";
Can I convert the data I got from I2C communication for using in the method for deserializeJson(jsonobj, stringofdata)
I2C communication side of arduino looks like,
void receiveEvent(size_t howMany) {
String datain = "";
while (0 < Wire.available()) {
char c = Wire.read();
datain += c;
}
Serial.println(datain);
//be careful can't send too much json data I2C crash!
Serial.println(datain.length());
DynamicJsonDocument datajson(100);
if (deserializeJson(datajson, datain)) {
Serial.print("deserialization ok ");
digitalWrite(13, HIGH);
delay(250);
digitalWrite(13, LOW);
f0 = datajson["f0"];
f1 = datajson["f1"];
f2 = datajson["f2"];
Serial.println(String(f0) + " " + String(f1) + " " + String(f2));
}
}
In serial monitor I only see this no deserialization worked
{"f0":0,"f1":0,"f2":0}
22
1 Answer 1
The mistake I did was thinking deserializeJson(datajson, datain)
gives a Boolean as true
for correct deserialization but accually it gives an object of DeserializationError err
so need to check if there is no error thus
The new code
// need ! here
if (!deserializeJson(datajson, datain)) {
Serial.println("yay it worked");
Serial.print("deserialization ok ");
digitalWrite(13, HIGH);
delay(250);
digitalWrite(13, LOW);
f0 = datajson["f0"];
f1 = datajson["f1"];
f2 = datajson["f2"];
Serial.print(f0);
Serial.print(" ");
Serial.print(f1);
Serial.print(" ");
Serial.println(f2);
//also tested this way and it works too
Serial.println(String(f0) + " " + String(f1) + " " + String(f2));
} else {
// I was coding here thinking its Boolean before
//error
}
-
1For reference, here is the documentation of
deserializeJson()
.Benoit Blanchon– Benoit Blanchon2022年02月23日 07:31:42 +00:00Commented Feb 23, 2022 at 7:31
" "
) with +. That just adds the pointer addresses together.DeserializationError error
error
inside if condition still no luckarduino if (err) { Serial.print(F("deserializeJson() failed: ")) Serial.println(err.c_str()) } else { //your code }