YOGYUI
ArduinoJson Document - Key 존재 여부 확인 본문
반응형
공식 API 문서 참고(링크)
메서드 이름: containsKey()
bool containsKey(const char* key) const;
bool containsKey(const String& key) const;
bool containsKey(const std::string& key) const;
bool containsKey(const __FlashStringHelper& key) const;
[예시]
StaticJsonDocument<256> doc;
JsonObject root = doc.to<JsonObject>();
root["city"] = "Paris";
bool hasCity = root.containsKey("city"); // true
bool hasCountry = root.containsKey("country"); // false
공식 가이드라인에 따르면 containsKey 메서드 호출은 수행 시간이 오래 걸리니 정말 특별한 경우가 아니라면 사용하지 않기를 권장 (아키텍쳐 특성상 고속 정렬 알고리즘이 불가능해서 그럴지도?)
존재하지 않는 key 접근 시 Null을 반환하므로 이를 활용하면 된다고 한다
[권장 구현 방안]
/* Null Check by JsonVariant */
JsonVariant error = root["error"];
if (!error.isNull()) {
Serial.println(error.as<char*>());
return;
}
/* Simplified */
const char* error = root["error"];
if (error) {
Serial.println(error);
return;
}
반응형
'Hardware > Arduino' 카테고리의 다른 글
(CJMCU-2812-16) WS2812 RGB LED Array (x16 Ring) (0) | 2021.03.01 |
---|---|
ESP8266에서 MQTT 구동하기 (0) | 2021.02.01 |
Keyes ESP8266 WiFi Module (0) | 2021.01.31 |
Adafruit HT16K33 Backpack + LED Display (14-segment) (0) | 2021.01.28 |
Comments