简体   繁体   English

C++ 中的 Json 序列化(esp32)

[英]Json serializing in C++ (esp32)

I'm writing some script for esp32 and struggling to serialize a json.我正在为 esp32 编写一些脚本并努力序列化 json。

Used libraries are HTTPClient and ArduinoJson.使用的库是 HTTPClient 和 ArduinoJson。

String payload = http.getString();
Serial.println(payload);
deserializeJson(result, payload);
const char* usuario = result["user"];
Serial.println("##########");
Serial.println(usuario);

The received payload is:接收到的有效载荷为:

{"ip":"10.57.39.137","area":"[{\\"id\\":\\"3\\",\\"text\\":\\"BOX\\"}]","user":"[{\\"id\\":\\"6270\\",\\"text\\":\\"ANDRE LARA OLIVEIRA E SILVA\\"}]","teamId":6,"id":4,"siteId":2,"userCreate":"100059527","dateCreate":"2020-11-19T08:49:03.957","userUpdate":null,"dateUpdate":null}

and i need to retrieve id and text from "user" key.我需要从“用户”键中检索 id 和文本。 Its fine to deserielize and retrieve user object.反序列化和检索用户对象很好。 But result["user"] returns [{"id":"6270","text":"ANDRE LARA OLIVEIRA E SILVA"}] to the char array.但是result["user"]返回[{"id":"6270","text":"ANDRE LARA OLIVEIRA E SILVA"}]到字符数组。 So it's something like a json nested to a array... and it's not working out to deserialize.所以它就像一个嵌套在数组中的 json ......并且它无法反序列化。

Can anyone help me how to properly get the "id" and "text" values from "user" object?任何人都可以帮助我如何从“用户”对象正确获取“id”和“text”值?

Thanks!谢谢!

"Can anyone help me how to properly get the "id" and "text" values from "user" object?" “任何人都可以帮助我如何从“用户”对象正确获取“id”和“text”值?” You can access them with您可以访问它们

const char *id = result["user"]["id"];
const char *text = result["user"]["text"];

Try:尝试:

const int id = result["user"]["id"];
const char* text = result["user"]["text"];

The library doesn't know the content of that string is valid JSON, so you have re-parse it.该库不知道该字符串的内容是有效的 JSON,因此您已重新解析它。 This code worked for me on my PC, though I don't have an Arduino to test it on:这段代码在我的 PC 上对我有用,但我没有 Arduino 来测试它:

auto payload = "..."; // JSON content here
StaticJsonDocument<1024> result;
deserializeJson(result, payload);
auto user = result["user"].as<const char*>();

StaticJsonDocument<256> userObj;
deserializeJson(userObj, user);
auto id = userObj[0]["id"].as<int>();
auto text = userObj[0]["text"].as<const char*>();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM