0

I'm trying my hands on arduino. Doing a POST request with some data to a server. But i'm not able to do a proper formatting of that data. I'm using arduinojson for it but i'm not sure whether i'm doing it correctly or not.

#include <ESP8266WiFi.h>
#include <ESP8266HTTPClient.h>
#include <ArduinoJson.h>
uint8_t measure = 0;

void setup() {
  // Wifisetup code
}

void loop() {
  StaticJsonDocument<1000> doc;
  Serial.println("Collecting measures");
  JsonArray data = doc.createNestedArray("data");

  for (int i = 0; i < 500; i++) {
    measure = analogRead(A0);
    measure = measure/2;
    data.add(measure);
    delay(10);
  }

  String json;
  serializeJson(doc["data"], json);
  Serial.println(json);

  HTTPClient http;
  http.begin("http://04f62766ea3b.ngrok.io/ecg_data.json");

  http.POST(json);
  http.end();
}

But at the rails server end, I'm getting response like this:

Parameters: {"0,0,2,2,2,2,1,2,1,2,0,2,1,2,1,2,1,2,1,2,1,2,1,2,1,2,1,2,1,2,1,3,1,2,1,2,1,2,1,2,1,2,1,2,1,2,2,2,1,2,1,1,1,2,1,2,1,2,1,2,1"=>nil}

But it should be in a way like:

{ "data" => [0,0,2,2,2...] }

Let me know what is needed to be done in order to proper formatting.

Ahmad hamza
  • 1,816
  • 1
  • 23
  • 46
  • 2
    `serializeJson(doc["data"], json);` only serialised the array, not the entire data object. change it to `serializeJson(doc, json);`. – hcheung Jun 14 '20 at 08:19
  • But i also had to add `Content-Type` as `application/json` mentioned here: https://github.com/esp8266/Arduino/blob/master/libraries/ESP8266HTTPClient/examples/PostHttpClient/PostHttpClient.ino#L56 – Ahmad hamza Jun 14 '20 at 09:09

0 Answers0