使用ArduinoJson库的JsonObject无法解析Json

jgwigjjp  于 2023-05-08  发布在  其他
关注(0)|答案(2)|浏览(271)

我使用以下代码使用SPIFFS将Config.json文件存储到ESP32闪存中

#include <ArduinoJson.h>
#include <FS.h>
#include<SPIFFS.h>

bool loadConfig() {
File configFile = SPIFFS.open("/Config.json", "r");
if (!configFile) {
Serial.println("Failed to open config file");
return false;
}

size_t size = configFile.size();
if (size > 1024) {
Serial.println("Config file size is too large");
return false;
}

// Allocate a buffer to store contents of the file.

std::unique_ptr<char[]> buf(new char[size]);

// We don't use String here because ArduinoJson library requires the input
// buffer to be mutable. If you don't use ArduinoJson, you may as well
// use configFile.readString instead.

configFile.readBytes(buf.get(), size);
Serial.println(buf.get());

StaticJsonBuffer<1024> jsonBuffer;
JsonObject& json = jsonBuffer.parseObject(buf.get());

if (!json.success()) {
Serial.println("Failed to parse config file");
return false;
}

const char* ssid = json["ssid"];
const char* password = json["password"];

// Real world application would store these values in some variables for
// later use.

Serial.print("Loaded ssid: ");
Serial.println(ssid);
Serial.print("Loaded password: ");
Serial.println(password);
return true;
}

void setup() {
Serial.begin(115200);
Serial.println("");
delay(1000);
Serial.println("Mounting FS...");
if (!SPIFFS.begin()) {
Serial.println("Failed to mount file system");
return;
}



if (!loadConfig()) {
  
Serial.println("Failed to load config");

} 

else {
Serial.println("Config loaded");
}

}

void loop() {
yield();

}

但是解析失败,我在串行监视器上得到以下消息:安装FS...解析配置文件失败无法加载配置

  • 我的Arduino IDE版本:1.8.13(Windows)
  • 配置文件有2个对象:
{
        "ssid": "ESP32",
        "password": "Softronics"    
      }

先谢谢你了

xwbd5t1u

xwbd5t1u1#

不需要预先分配缓冲区来存储ArduinoJSON的文件。ArduinoJSON是quite capable of reading the file itself,避免了为文件管理缓冲区的需要。
这个代码是不必要的。不应分配缓冲区。

std::unique_ptr<char[]> buf(new char[size]);

// We don't use String here because ArduinoJson library requires the input
// buffer to be mutable. If you don't use ArduinoJson, you may as well
// use configFile.readString instead.

configFile.readBytes(buf.get(), size);
Serial.println(buf.get());

StaticJsonBuffer<1024> jsonBuffer;
JsonObject& json = jsonBuffer.parseObject(buf.get());

if (!json.success()) {
Serial.println("Failed to parse config file");
return false;
}

下面是一个完整的程序,它对我来说是正确的:

#include <ArduinoJson.h>
#include <FS.h>
#include<SPIFFS.h>

bool loadConfig() {
  File configFile = SPIFFS.open("/Config.json", "r");
  if (!configFile) {
    Serial.println("Failed to open config file");
    return false;
  }

  size_t size = configFile.size();
  if (size > 1024) {
    Serial.println("Config file size is too large");
    return false;
  }

  StaticJsonDocument<1024> doc;
  DeserializationError error = deserializeJson(doc, configFile);

  if(error) {
    Serial.println("Failed to parse config file");
    return false;
  }

  const char* ssid = doc["ssid"];
  const char* password = doc["password"];

  // Real world application would store these values in some variables for
  // later use.

  Serial.print("Loaded ssid: ");
  Serial.println(ssid);
  Serial.print("Loaded password: ");
  Serial.println(password);
  return true;
}

void setup() {
  Serial.begin(115200);
  Serial.println("");
  delay(1000);
  Serial.println("Mounting FS...");
  if (!SPIFFS.begin()) {
    Serial.println("Failed to mount file system");
    return;
  }

  if (!loadConfig()) {
    Serial.println("Failed to load config");
  } 
  else {
    Serial.println("Config loaded");
  }
}

void loop() {
  yield();

}

你发布的代码是ArduinoJSON版本5,已经过时了。使用ArduinoJSON版本6。您应该升级您的库以使用它。
在编写使用该库的代码时,ArduinoJSON documentation和示例非常有用。
另外,请尝试缩进您的代码,至少是出于对他人的礼貌,如果不是为了帮自己一个忙。适当的缩进会使代码更具可读性。

az31mfrm

az31mfrm2#

要解析ArduinoJSON,只需要

String JSONpayload = "some JSON here";
  StaticJsonDocument <512> geoLocationInfoJson;
  DeserializationError error = deserializeJson(geoLocationInfoJson, JSONpayload);
  if (error) {
    this->mserial->printStrln("Error deserializing JSON");
  }

要使用StaticJsonDocument中的值,首先需要

if ( geoLocationInfoJson.isNull() == true ){
  String dataStr="NULL geoLocation data.\n";
  Serial.print( dataStr); 
  return true;
}

接下来需要验证密钥是否存在。如果为TRUE,则必须首先将所需的值转换为相应的数据类型,如下所示,然后才能对其进行处理,例如,将其作为BLE消息字符串发送:

if(this->interface->geoLocationInfoJson.containsKey("lat")){
  float lat = this->interface->geoLocationInfoJson["lat"];
  dataStr += "Latitude: "+ String(lat,4) + "\n";
}
if(this->interface->geoLocationInfoJson.containsKey("lon")){
  float lon = this->interface->geoLocationInfoJson["lon"];
  dataStr += "Longitude: "+ String(lon,4) + "\n";
}

if(this->interface->geoLocationInfoJson.containsKey("regionName"))
  dataStr += String(this->interface->geoLocationInfoJson["regionName"].as<char*>()) + ", ";

上面的完整代码可以在这个GitHub存储库中找到:
https://github.com/aeonSolutions/aeonlabs-ESP32-C-Base-Firmware-Libraries

相关问题