0

I'm writing some script for ESP32 and struggling to serialize a json.

Used libraries are HTTPClient and 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}

I need to retrieve id and text from "user" key. It's fine to deserialize and retrieve user object. But result["user"] returns: [{"id":"6270","text":"ANDRE LARA OLIVEIRA E SILVA"}] to the char array. So it's something like a json nested in an array... and it's not working out to deserialize.

Can anyone help me how to properly get the "id" and "text" values from "user" object?

ocrdu
  • 2,172
  • 6
  • 15
  • 22
alosbh
  • 25
  • 5

3 Answers3

0

"Can anyone help me how to properly get the "id" and "text" values from "user" object?" You can access them with

const char *id = result["user"]["id"];
const char *text = result["user"]["text"];
Thomas Sablik
  • 16,127
  • 7
  • 34
  • 62
0

Try:

const int id = result["user"]["id"];
const char* text = result["user"]["text"];
ocrdu
  • 2,172
  • 6
  • 15
  • 22
  • Thank you ocrdu. I already tried this approach but it returns me blank. Bad thing about my hardware is that i dont have a debugging interface. so im limited to serial printing. – alosbh Nov 19 '20 at 15:18
0

The library doesn't know the content of that string is valid JSON, so you have re-parse it. This code worked for me on my PC, though I don't have an Arduino to test it on:

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*>();
parktomatomi
  • 3,851
  • 1
  • 14
  • 18