Interpret the JSON response of a Webservice that was called by Arduino

Asked

Viewed 898 times

1

How do I interpret information from a Webservice who was called by the Arduino?

Webservice returns a JSON and I need to interpret it. An example of the answer can be seen below:

[{"valor":"10"}] 

The code below, obtained from that website, shows the call and the interpretation, but is read one byte at a time and, therefore, I have doubts of how could do this for the return in JSON.

The part that reads one byte at a time can be seen below:

if (client.available()) {
  char c = client.read();
  Serial.print(c);
}

Complete code:

#include <SPI.h>
#include <Ethernet.h>

// Enter a MAC address for your controller below.
// Newer Ethernet shields have a MAC address printed on a sticker on the shield
byte mac[] = { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED };
// if you don't want to use DNS (and reduce your sketch size)
// use the numeric IP instead of the name for the server:
//IPAddress server(74,125,232,128);  // numeric IP for Google (no DNS)
char server[] = "www.google.com";    // name address for Google (using DNS)

// Set the static IP address to use if the DHCP fails to assign
IPAddress ip(192, 168, 0, 177);

// Initialize the Ethernet client library
// with the IP address and port of the server
// that you want to connect to (port 80 is default for HTTP):
EthernetClient client;

void setup() {
  // Open serial communications and wait for port to open:
  Serial.begin(9600);
  while (!Serial) {
    ; // wait for serial port to connect. Needed for native USB port only
  }

  // start the Ethernet connection:
  if (Ethernet.begin(mac) == 0) {
    Serial.println("Failed to configure Ethernet using DHCP");
    // try to congifure using IP address instead of DHCP:
    Ethernet.begin(mac, ip);
  }
  // give the Ethernet shield a second to initialize:
  delay(1000);
  Serial.println("connecting...");

  // if you get a connection, report back via serial:
  if (client.connect(server, 80)) {
    Serial.println("connected");
    // Make a HTTP request:
    client.println("GET /search?q=arduino HTTP/1.1");
    client.println("Host: www.google.com");
    client.println("Connection: close");
    client.println();
  } else {
    // if you didn't get a connection to the server:
    Serial.println("connection failed");
  }
}

void loop() {
  // if there are incoming bytes available
  // from the server, read them and print them:
  if (client.available()) {
    char c = client.read();
    Serial.print(c);
  }

  // if the server's disconnected, stop the client:
  if (!client.connected()) {
    Serial.println();
    Serial.println("disconnecting.");
    client.stop();

    // do nothing forevermore:
    while (true);
  }
}
  • 1

    https://www.arduino.cc/en/Tutorial/WebClient

  • 1

    Related: http://answall.com/questions/101273/como-fazer-uma-requisi%C3%A7%C3%A3o-http-get-para-um-web-service-com-o-Arduino

  • I don’t quite understand what Arduino has to do with the webservice, if in fact who connects in the webservice is c and it seems that it has nothing to do with the "Serial" part. I could explain, maybe it helps to understand your doubt.

  • @Guilhermenascimento, in the context of this question, who connects in Webservice is the Arduino. In the above code, the instructions that use the Serial are serving as a kind of logger to know what is happening in the program. Anyway, it connects to Webservice using Ethernet and uses Arduino’s Serial output to track that connection.

  • I believe that this question was closed erroneously. I do not know if before or after the author’s edition. The question is not so different from this one: http://answall.com/questions/101273/como-fazer-uma-requisi%C3%A7%C3%A3o-http-get-to-a-web-service-com-o-Arduino

  • @Cantoni understand that closing is almost never mistaken, if the question was closed is because the author has not made it clear, at the time the author improve the question can be reopened, note that this has been discussed several times, I recommend you to read this discussion of the goal: http://meta.pt.stackoverflow.com/a/2676/3635 The author did not make it clear in several ways, if you understood the doubt you can edit the question and improve it, so it automatically enters the voting process to reopen, will be 5 votes needed to reopen - I hope you understand ;)

  • @Cantoni actually is this question is duplicate the other, only there it seems clearer. If I had known the other would have voted as duplicate

  • @Guilhermenascimento, did not know that after an issue the question automatically enters the line to reopen. Good to know. Thanks for the clarification.

  • It is not the same thing. Note that this question here wishes to interpret the JSON response of a Webservice call. The other question quoted by me just wishes to make the call.

  • Okay, but here’s the question very confused and as I said if you know how to improve, then improve, this is the main foundation of Stackoverflow http://meta.pt.stackoverflow.com/q/2212/3635 - But edit without defacing and only if you’re sure @Cantoni.

  • 1

    @Guilhermenascimento, edited question. Thank you.

  • @Cantoni For nothing, just recommend that always encourage the author to edit by himself first, because sometimes (in other future questions) the author may want something else. ;)

Show 7 more comments

1 answer

2


Different from what happens in high-level languages like Python and PHP, in C (mainly in Arduino) when making a request, will be returned character by character of the web service and there are no functions ready to assist.

In case, if you print this on your serial, it will look like it all came at once, but make no mistake. To receive data from a web service you need to read the received data, byte by byte, save in a buffer. First you should filter the headers, since they are usually not useful, when receiving two /r/n you will know that the HTTP header is over, so buffer the body of your response.

When the client finishes the request, perform a parser in the buffer looking for your information. It’s really all in hand, it doesn’t have functions ready for this kind of situation and all the libraries I’ve used for parse JSON in C are heavy and spend almost all memory of the Arduino.

Example of how I take the response value and save it to a buffer

[... monte de código acima...]
while (http.connected()) {
            while (http.available()) {

                char read_char = http.read();
                Serial.print(read_char); /* Imprime resposta do servidor */

                if (read_char != '\n' && newLine != 1) {
                  resposta[i] = read_char;
                  i++;
                  resposta[i] = '\0';
                }

                if (read_char == '\n') {
                  newLine = 1;
                }
            }

            i = 0;
        }
[... monte de código abaixo....]

After that I have in the response variable what the server returned me, then I use the strtok to break the answer into pieces

In your example, you have the instruction char c = client.read(); That’s where you’ll get the answer from the server, the problem is that it only has one character, so you’ll have to go throwing it in an array to be able to read the whole answer. Then, at another point, when interpreting what came from the server, read this character array (string) and search for what you want

  • 1

    Post a code with a small example. It doesn’t have to be all, just the relevant part, that is, the part of putting together the request and the part of interpreting the answer. It will be of great help.

  • I don’t have a ready code but I have an example of the site of the Internet that looks like this one doesn’t read the returned parameters that can be json the same type text.

  • then, to read the parameters you need to create a logic that takes this data. I always use control characters, I read everything between Ipes or Cerquilha, give a split on these data and as I know the order of the elements, attribute to variables .

  • I understand @Carloscandido, the comment was for Renato to post a code. Anyway, as he said, you will need to write some code to interpret this JSON. Unless you have some Arduino library to help you with that.

  • It doesn’t have to be just json, it can be text even, I just need to get values returned from the Web Service with Arduino.

  • But this link has an example: https://www.arduino.cc/en/Tutorial/WebClient See this excerpt of the code in the loop: char c = client.read(); there is a 1 byte reading.

Show 1 more comment

Browser other questions tagged

You are not signed in. Login or sign up in order to post.