ESP32使用ArduinoJson从过滤后JSON提取RGB颜色值无输出问题求助
问题原因
- 路径缺少数组索引:JSON结构中
responses是数组类型,你提取颜色值的路径中doc["responses"]后未添加[0]索引取第一个元素,导致路径匹配失败,无法定位到对应字段。 - 变量类型不匹配:
red/green/blue三个字段都是整型数值,你使用const char*字符串类型接收,ArduinoJson的隐式类型转换会返回空指针,所以打印结果为空。
修正后的提取代码
const char* cObject = doc["responses"][0]["textAnnotations"][0]["description"]; // 补全responses数组的[0]索引,变量类型改为匹配数值的int int cRed = doc["responses"][0]["imagePropertiesAnnotation"]["dominantColors"]["colors"][0]["color"]["red"]; int cGreen = doc["responses"][0]["imagePropertiesAnnotation"]["dominantColors"]["colors"][0]["color"]["green"]; int cBlue = doc["responses"][0]["imagePropertiesAnnotation"]["dominantColors"]["colors"][0]["color"]["blue"]; Serial.print("cObject: "); Serial.println(cObject); Serial.print("cRed: "); Serial.println(cRed); Serial.print("cGreen: "); Serial.println(cGreen); Serial.print("cBlue: "); Serial.println(cBlue);
如果需要更稳妥避免隐式转换异常,可以显式指定转换类型,例如:doc["responses"][0]["imagePropertiesAnnotation"]["dominantColors"]["colors"][0]["color"]["red"].as<int>()。
内容的提问来源于stack exchange,提问作者Paulo Borges
相关产品推荐
相关产品推荐

