arduino(7):使用ESP8266,使用ArduinoJson库,进行Json序列化和反序列化

前言


相关arduino 全部分类:
https://blog.csdn.net/freewebsys/category_8799254.html

本文的原文连接是:
https://blog.csdn.net/freewebsys/article/details/104190356

未经博主允许不得转载。
博主地址是:http://blog.csdn.net/freewebsys

1,关于arduino Json


项目地址:
https://github.com/bblanchon/ArduinoJson

里面封装了,Json 相关的使用方法,对于数据上报帮助非常大。
同时对于数据解析作用也特别大。

2,使用


直接克隆项目代码到 libraries 就行。然后重启 arduino IDE 就可以使用了。

#include <ArduinoJson.h>

void setup() {

  Serial.begin(9600);
    
  DynamicJsonDocument doc(1024);
 
  // WARNING: the string in the input  will be duplicated in the JsonDocument.
  String input = "{\"sensor\":\"gps\",\"time\":1351824120,\"data\":[48.756080,2.302038]}";
  deserializeJson(doc, input);
  JsonObject obj = doc.as<JsonObject>();

  // You can use a String to get an element of a JsonObject
  // No duplication is done.
  long time = obj[String("time")];
  String sensor = obj["sensor"];
  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);

  obj["sensor"] = "new gps";
  obj["code"] = 200;
  // Lastly, you can print the resulting JSON to a String
  String output;
  serializeJson(doc, output);

  Serial.println(output);
}

void loop() {
  // not used in this example
}

deserializeJson(doc, input); 反序列化, serializeJson(doc, output); 将object 对象转换成 string。
和 java 的fastjson 类似。
DynamicJsonDocument doc(1024); JsonObject obj = doc.as();
创建了一个动态json。然后设置属性。

在ESP8266 上面运行效果:

1351824120
48.756081
2.302038
{"sensor":"new gps","time":1351824120,"data":[48.75608,2.302038],"code":200}

3,总结


arduino 现在已经非常的成熟了,是一个非常成熟的解决方案了。
JSON 也是常用的lib 库,可以进行json的序列化,和转换做数据通讯了。
无论是 使用 rest mqtt socket 的时候都是需要和服务端进行数据通讯的。
使用起来也特别的方便。

本文的原文连接是:
https://blog.csdn.net/freewebsys/article/details/104190356

博主地址是:https://blog.csdn.net/freewebsys

发布了639 篇原创文章 · 获赞 260 · 访问量 211万+

猜你喜欢

转载自blog.csdn.net/freewebsys/article/details/104190356