ArduinoJson value field returns 'null' after multiple updates

Hi everyone,

I'm working on a sketch in which I'm trying to send gps data over gprs, which I am serializing using ArduinoJson.

The json data has the form:

{"coordinates":[111111111,222222222],"status":true,"time":"012345678912","velocity":0.11111}

I ran into unexpected behaviour (at least for me) of the ArduinoJson library. After the timestamp field is updated a couple of times, it shows as '"time":null'. I made a small sketch to reproduce my problem. This allows updating and serializing the json object with data from the serial port:

#include <ArduinoJson.h>
const size_t capacity = JSON_ARRAY_SIZE(2) + JSON_OBJECT_SIZE(4) + 46; // from https://arduinojson.org/v6/assistant/
DynamicJsonDocument doc(capacity);

JsonArray coordinates = doc.createNestedArray("coordinates");

int counter;
char buf[15]; // char array for timestamp

void setup() {
  Serial.begin(115200);
  coordinates.add(111111111);
  coordinates.add(222222222);
  doc["status"] = true;
  doc["time"] = "111111111111";
  doc["velocity"] = 0.11111;

}

void loop() {
  serializeJson(doc, Serial);
  Serial.println("");
  while (!Serial.available()) {
    ;
  }
  while (true) {
    Serial.print(counter);
    if (counter > 13) {
      buf[counter] = '\0';
      Serial.println(" Null");
      break;
    }
    buf[counter] = Serial.read();
    Serial.print(" ");
    Serial.println(buf[counter]);
    if (buf[counter] == '\r') {
      buf[counter] = '\0';
      break;
    }
    
    counter++;
  }
  doc["time"] = buf; //update field in place, works only a couple of times
  counter = 0;
}

If "abcdefghijkl" is inserted more than three times, the "time"-value becomes null:

{"coordinates":[111111111,222222222],"status":true,"time":"111111111111","velocity":0.11111}
0 a
1 b
2 c
3 d
4 e
5 f
6 g
7 h
8 i
9 j
10 k
11 l
12 

{"coordinates":[111111111,222222222],"status":true,"time":"abcdefghijkl","velocity":0.11111}
0 a
1 b
2 c
3 d
4 e
5 f
6 g
7 h
8 i
9 j
10 k
11 l
12 

{"coordinates":[111111111,222222222],"status":true,"time":"abcdefghijkl","velocity":0.11111}
0 a
1 b
2 c
3 d
4 e
5 f
6 g
7 h
8 i
9 j
10 k
11 l
12 

{"coordinates":[111111111,222222222],"status":true,"time":"abcdefghijkl","velocity":0.11111}
0 a
1 b
2 c
3 d
4 e
5 f
6 g
7 h
8 i
9 j
10 k
11 l
12 

{"coordinates":[111111111,222222222],"status":true,"time":null,"velocity":0.11111}

Increasing the capacity of the JsonDocument increases the number of times the value can be changed but the end result is the same.

Is this how the capacity works and do I need to take care of freeing the memory or is this a bug?

This is on an Arduino Uno. ArduinoJson library version is most recent: 6.12.0

Thanks in advance!

Hi! I have the same issue. Did you resolve it?

UPD. Looks like

jsonDoc.clear();

or

jsonDoc.to<JsonObject>();

solving the problem

Note:

StaticJsonDocument<1000> jsonDoc;