0

I guess that my problems are because I'm new to C, but after spending three evenings without success I thought I'd give it a try to ask here!

I receive a JSON-formatted string in a UDP message. It contains several values that I would like to catch and convert to variables. The string format is like this:

{
  "U1": 224,
  "U2": 227,
  "U3": 224,
  "I1": 0,
  "I2": 0,
  "I3": 0,
  "P": 0,
  "PF": 0,
  "E pres": 639,
  "E total": 69901578,
  "Serial": "16889379",
  "Sec": 393833
}

Actually I really only need to get values U1, U2, U3 and I1, I2, I3. I'm grateful for all the help I can get solving this!

Best regards Per

1

Two possible approaches:

  1. Tokenize the string using strtok(), probably a few levels deep. This may require you learning quite a bit more about C++, pointers, and character arrays as strings.
  2. An excellent opportunity to use an existing library, such as ArduinoJSON, which abstracts out the difficulties you may encounter if the fields in your JSON string arrive in a different order, etc.

An example of using ArduinoJSON for your case is shown in the documentation (excerpted/adapted from Decoding JSON)

#include <ArduinoJson.h>

// [...] other code

char json[] = "{ \"U1\": 224, \"U2\": 227, \"U3\": 224, \"I1\": 0, \"I2\": 0, \"I3\": 0, \"P\": 0, \"PF\": 0, \"E pres\": 639, \"E total\": 69901578, \"Serial\": "16889379", \"Sec\": 393833 }";

//
// Step 1: Reserve memory space
//
StaticJsonBuffer<200> jsonBuffer;

//
// Step 2: Deserialize the JSON string
//
JsonObject& root = jsonBuffer.parseObject(json);

if (!root.success())
{
  Serial.println("parseObject() failed");
  return;
}

//
// Step 3: Retrieve the values
//
uint16_t    u1 = root["U1"];
uint16_t    u2 = root["U2"];
uint16_t    u3 = root["U3"];
uint16_t    i1 = root["I1"];
uint16_t    i2 = root["I2"];
uint16_t    i3 = root["I3"];

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.