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

dda
1,5951 gold badge12 silver badges17 bronze badges
asked Aug 22, 2017 at 15:56
1
  • Have you tried iterating over the string? Commented Aug 22, 2017 at 16:02

1 Answer 1

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"];
answered Aug 22, 2017 at 16:15

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.