首页 > 解决方案 > 如何从 Arduino IDE 中的字符串变量解析 json 字符串

问题描述

我想用 Arduino 中的变量解析 json 字符串。我是编码新手,所以面临一些困难。这是我的代码:


#include <ArduinoJson.h>
#define LED_1 23
void setup() {
  Serial.begin(9600);
  pinMode(LED_1, OUTPUT);
  digitalWrite(LED_1, HIGH);
  while (!Serial) continue;
  StaticJsonBuffer<200> jsonBuffer;

//These are the variable that I want to use in below json[] string
String sensor_id = "gps_1245";
String reg_time = "110520191445";
String sensor_direction = "[48.756080,2.302038]";

// this is the json[] string that I want to use above variables(sensor_id, reg_time, sensor_direction).

char json[] =  "{\"sensor_id\":\"gps_1245\",\"reg_time\":110520191445,\"sensor_direction\":[48.756080,2.302038]}";

JsonObject& root = jsonBuffer.parseObject(json);
  // Test if parsing succeeds.
  if (!root.success()) {
    Serial.println("parseObject() failed");
    return;
  }
  const char* sensor = root["sensor_id"];
  long time = root["reg_time"];
  double latitude = root["sensor_direction"][0];
  double longitude = root["sensor_direction"][1];

  // Print values.
  Serial.println(sensor);
  Serial.println(time);
  Serial.println(latitude, 6);
  Serial.println(longitude, 6);
}
void loop() {
  digitalWrite(LED_1, LOW);
  delay(300);
  digitalWrite(LED_1, HIGH);
  delay(300);
  digitalWrite(LED_1, LOW);
  delay(300);
}

此代码有效,但我需要使用变量。所以请帮我解决这个任务。我正在为这段代码使用 Arduino IDE。谢谢你

标签: jsonarduino

解决方案


推荐阅读