Go Down

Topic: Arduino fails to Post data to web api (Read 299 times) previous topic - next topic


Oct 13, 2017, 04:11 am Last Edit: Oct 13, 2017, 04:17 am by JustGoFly
Follow instruction - compile and run.  The example shows you how to make the body of your html response (NOT THE HEADER).  if you need help with the header - let me know. I haven't read the whole thread, so hopefully this is helpful.  It demonstrates how to keep your variables integer in your JSON result, but also - as you requested provide them in string form.

I am trying to keep this simple readable. There are alot of ways to skin this cat, and a cool class the builds your full response, with header+body and cool addJson function may be preferable. But this will get the job done, and makes your code a little more readable. It also does NOT write to anything more than the console. So it is intended to demonstrate how to use the two Fmt functions and make your JSON pretty and readable.

See if this helps:
Make a new project - testJson.
Add a new tab onto your project. Call it FormatJSON.h
or just paste both code inserts into the main project, then remove the #include statement.
Code: [Select]

static String Fmt(String first, String second, bool last=false)
  String response;
  response = "\t\"" + first + "\":\"" + second + "\"";
  if (!last)
      response +=",";
  response +="\r\n";
  return response;

static String Fmt(String first, uint32_t second, bool last=false)
  String response;
  response = "\t\"" + first + "\":" + String(second);
  if (!last)
      response +=",";
  response +="\r\n";
  return response;

and in your main tab - make it look like this:

Code: [Select]
#include "FormatJson.h"
/* one of the desired formats, I also show an integer JSON result example

#define LAST true
void setup() {
    uint32_t Humidity=4;
    uint32_t TemperatureC=52;
    uint32_t TemperatureF=35;
    uint32_t HeatIndexC=53;
    uint32_t HeatIndexF=54;
    uint32_t Max=43;
    uint32_t Min=75;
    Serial.println("First example shows a numeric Json result");
    String json="{\r\n";
    json+=Fmt("Humidity",     Humidity);
    json+=Fmt("TemperatureC", TemperatureC);
    json+=Fmt("TemperatureF", TemperatureF);
    json+=Fmt("HeatIndexC",   HeatIndexC);
    json+=Fmt("HeatIndexF",   HeatIndexF);
    json+=Fmt("Max",          Max);
    json+=Fmt("Min",          Min, LAST);
    Serial.println("Second example shows a string Json result");
    json+=Fmt("Humidity",     String(Humidity));
    json+=Fmt("TemperatureC", String(TemperatureC));
    json+=Fmt("TemperatureF", String(TemperatureF));
    json+=Fmt("HeatIndexC",   String(HeatIndexC));
    json+=Fmt("HeatIndexF",   String(HeatIndexF));
    json+=Fmt("Max",          String(Max));
    json+=Fmt("Min",          String(Min),  LAST);

void loop() {

Go Up