0

I'm using asyncHTTPrequest for async request to a REST API in ESP8266. I receive the response in JSON format but can't parse it.

This kind of parsing was working while i used to made sync call to API.

I tried to store the request->responseText() into a String variable because its return a String, but the variable never get any value.

void sendRequest() {
  if (request.readyState() == 0 || request.readyState() == 4) {
    request.open("GET", "http://192.168.1.103:45456/api/systems/1013/arduino");
    request.send();
  }
}

void requestCB(void* optParm, asyncHTTPrequest* request, int readyState) {
  if (readyState == 4) {  
    Serial.println(request->responseText()); 
    const size_t capacity = JSON_ARRAY_SIZE(1) + JSON_ARRAY_SIZE(2) + JSON_OBJECT_SIZE(2) + 2*JSON_OBJECT_SIZE(4) + JSON_OBJECT_SIZE(8)+816;
    DynamicJsonBuffer jsonBuffer(capacity);
    JsonObject& root = jsonBuffer.parseObject(request->responseText());
    String a = request->responseText();
    Serial.println(a);

    JsonObject& schState = root["dataForArduino"][0];

    String beginTime = schState["start"]; // "2019-12-02T21:51:00" 
  }
}

void setup() {
  Serial.begin(9600);

  wifi.Connect();
  request.onReadyStateChange(requestCB);
  ticker.attach(5, sendRequest);
}
Ben T
  • 4,656
  • 3
  • 22
  • 22
Matei Emil
  • 65
  • 9
  • Can you include an example JSON payload that you trying to decode? – Ben T Apr 13 '20 at 12:08
  • Have you cecked in your callback wether the readyState is really 4 when receiving the JSON, since you call on state change I would simply check with a Serial.print("readyState = ");Serial.println(readyState); as first line of the callback function – Codebreaker007 Apr 14 '20 at 09:13

2 Answers2

0

I have wrote json parsing function (__get_from_json) to get key value from json here

e.g. if you have json response like

{ 
 "timestamp" : "2020-04-01 19:20:49"
}

and in your application you want to parse timestamp value from it then

char response[max_response_size] = "{ \"timestamp\" : \"2020-04-01 19:20:49\" }";
char key[max_key_size] = "timestamp";
char value[max_value_size] = "";

if( __get_from_json( response, key, value, max_value_size ) ){

  Serial.println(value);
}
Suraj Inamdar
  • 181
  • 1
  • 1
0

I had the same problem and added .c_str() to get the response to print.

So in your example it would be:

String a = request->responseText();
Serial.println(a.c_str());

For the JSON I also needed to add .c_str()

DynamicJsonDocument jsonDoc(2048);
DeserializeJson(jsonDoc, a.c_str());
SCouto
  • 7,808
  • 5
  • 32
  • 49