首先安装ArduinoJSON library库,我选择了最新的6.14.0版本,注意网上有的例程是基于低于6.14版本的,如果你安装的是6.14,然后语法是5.0版本的那是无法编译通过的。
ArduinoJSON官网文档
JOSN助手
ArduinoJson示例
直接贴库自带的例程:
// ArduinoJson - arduinojson.org
// Copyright Benoit Blanchon 2014-2020
// MIT License
//
// This example shows how to generate a JSON document with ArduinoJson.
//
// https://arduinojson.org/v6/example/generator/
#include <ArduinoJson.h>
void setup() {
// Initialize Serial port
Serial.begin(9600);
while (!Serial) continue;
// Allocate the JSON document
//
// Inside the brackets, 200 is the RAM allocated to this document.
// Don't forget to change this value to match your requirement.
// Use arduinojson.org/v6/assistant to compute the capacity.
StaticJsonDocument<200> doc;
// StaticJsonObject allocates memory on the stack, it can be
// replaced by DynamicJsonDocument which allocates in the heap.
//
// DynamicJsonDocument doc(200);
// Add values in the document
//
doc["sensor"] = "gps";
doc["time"] = 1351824120;
// Add an array.
//
JsonArray data = doc.createNestedArray("data");
data.add(48.756080);
data.add(2.302038);
// Generate the minified JSON and send it to the Serial port.
//
serializeJson(doc, Serial);
// The above line prints:
// {"sensor":"gps","time":1351824120,"data":[48.756080,2.302038]}
// Start a new line
Serial.println();
// Generate the prettified JSON and send it to the Serial port.
//
serializeJsonPretty(doc, Serial);
// The above line prints:
// {
// "sensor": "gps",
// "time": 1351824120,
// "data": [
// 48.756080,
// 2.302038
// ]
// }
}
void loop() {
// not used in this example
}
我自己拼装JSON数据的例程
#include <ArduinoJson.h>
int x;
char webpage[40];//
// Allocate JsonBuffer
// Use arduinojson.org/assistant to compute the capacity.
StaticJsonDocument<30> doc;//注意doc大小根据需求调整
void setup() {
// put your setup code here, to run once:
Serial.begin(115200);
delay(10);
Serial.println();
}
void loop() {
// put your main code here, to run repeatedly:
doc["ADC"] = x++; //Put ADC value
doc["value"] = 2 * x;
Serial.println("serializeJson(doc, Serial)输出");
serializeJson(doc, Serial);
Serial.println("\r\n");
Serial.println("serializeJson(doc, webpage)输出");
serializeJson(doc, webpage);//给网页返回数据用此方法
Serial.println(webpage);
Serial.println("-------------------------");
delay(1000);
}
串口输出
解析从网站获取的JSON数据
#include <ESP8266WiFi.h>
#include <WiFiClient.h>
#include <ESP8266HTTPClient.h>
#include <ArduinoJson.h>
const char* wifiName = "你的WIFI SSID";
const char* wifiPass = "WIFI 密码";
//Web Server address to read/write from
const char *host = "http://arduinojson.org/example.json";
void setup() {
Serial.begin(115200);
delay(10);
Serial.println();
Serial.print("Connecting to ");
Serial.println(wifiName);
WiFi.begin(wifiName, wifiPass);
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
Serial.println("");
Serial.println("WiFi connected");
Serial.println("IP address: ");
Serial.println(WiFi.localIP()); //You can get IP address assigned to ESP
}
void loop() {
HTTPClient http; //Declare object of class HTTPClient
Serial.print("Request Link:");
Serial.println(host);
http.begin(host); //Specify request destination
int httpCode = http.GET(); //Send the request
String payload = http.getString(); //Get the response payload from server
Serial.print("Response Code:"); //200 is OK
Serial.println(httpCode); //Print HTTP return code
Serial.print("Returned data from Server:");
Serial.println(payload); //Print request response payload
if(httpCode == 200)
{
// Allocate JsonBuffer
// Use arduinojson.org/assistant to compute the capacity.
const size_t capacity = JSON_OBJECT_SIZE(3) + JSON_ARRAY_SIZE(2) + 60;
StaticJsonDocument<capacity> jsonBuffer;
// Parse JSON object解析 JSON
deserializeJson(jsonBuffer, payload);
JsonObject object = jsonBuffer.as<JsonObject>();
// Decode JSON/Extract values
//提取JSON里的数值
Serial.println(F("Response:"));
Serial.println(object["time"].as<String>());
Serial.println(object["data"][0].as<String>());
Serial.println(object["data"][1].as<String>());
}
else
{
Serial.println("Error in response");
}
http.end(); //Close connection
delay(5000); //GET Data at every 5 seconds
}
结果输出
Arduino IDE自带的示例
// ArduinoJson - arduinojson.org
// Copyright Benoit Blanchon 2014-2020
// MIT License
//
// This example shows how to deserialize a JSON document with ArduinoJson.
//
// https://arduinojson.org/v6/example/parser/
#include <ArduinoJson.h>
void setup() {
// Initialize serial port
Serial.begin(115200);
while (!Serial) continue;
// Allocate the JSON document
//
// Inside the brackets, 200 is the capacity of the memory pool in bytes.
// Don't forget to change this value to match your JSON document.
// Use arduinojson.org/v6/assistant to compute the capacity.
StaticJsonDocument<200> doc;
// StaticJsonDocument<N> allocates memory on the stack, it can be
// replaced by DynamicJsonDocument which allocates in the heap.
//
// DynamicJsonDocument doc(200);
// JSON input string.
//
// Using a char[], as shown here, enables the "zero-copy" mode. This mode uses
// the minimal amount of memory because the JsonDocument stores pointers to
// the input buffer.
// If you use another type of input, ArduinoJson must copy the strings from
// the input to the JsonDocument, so you need to increase the capacity of the
// JsonDocument.
char json[] =
"{\"sensor\":\"gps\",\"time\":1351824120,\"data\":[48.756080,2.302038]}";
// Deserialize the JSON document
DeserializationError error = deserializeJson(doc, json);
// Test if parsing succeeds.
if (error) {
Serial.print(F("deserializeJson() failed: "));
Serial.println(error.c_str());
return;
}
// Fetch values.
//
// Most of the time, you can rely on the implicit casts.
// In other case, you can do doc["time"].as<long>();
const char* sensor = doc["sensor"];
long time = doc["time"];
double latitude = doc["data"][0];
double longitude = doc["data"][1];
// Print values.
Serial.println(sensor);
Serial.println(time);
Serial.println(latitude, 6);
Serial.println(longitude, 6);
}
void loop() {
// not used in this example
}
// See also
// --------
//
// https://arduinojson.org/ contains the documentation for all the functions
// used above. It also includes an FAQ that will help you solve any
// deserialization problem.
//
// The book "Mastering ArduinoJson" contains a tutorial on deserialization.
// It begins with a simple example, like the one above, and then adds more
// features like deserializing directly from a file or an HTTP request.
// Learn more at https://arduinojson.org/book/
// Use the coupon code TWENTY for a 20% discount ❤❤❤❤❤