PDA

View Full Version : JSON Post Help



rhb327
25th April 2017, 03:51
{
"request":"senddata",
"datatype" : "event",
"id" : "123123",
"eventKey":"High Temperature",
"timestamp":"2017-01-13T20:15:57Z",
"eventParameters":{
"Temperature": 25,
"High Temperature": 35,
"Setpoint": 25,
}
}

For the above JSON, I've tried to use a QJsonDocument object like this:


QByteArray arr = "{\"request\" : \"senddata\","
"\"datatype\" : \"event\","
"\id\" : \"123123\","
"\"eventKey\" : \"High Temperature\","
"\timestamp\" : \"";
arr + dt;
arr += "\","
"\eventParameters\" : {"
"\"Temperature\" : 25,"
"\"High Temperature\" : 30,"
"\"Setpoint\" : 25}}";
doc = QJsonDocument::fromJson(arr);


I need this because the timestamp key is a variable. I can't get this to work properly. I've also tried using the insert method with QJsonObjec more like:


json.insert("id","070707");
json.insert("request","senddata");
json.insert("datatype","event");
json.insert("eventKey","High Temperature");
json.insert("timestamp", QDateTime::currentDateTime().toTimeSpec(Qt::Offset FromUTC).toString(Qt::ISODate));
...


No joy here either. So my real question is how to prepare the nested JSON example for a REST type POST command. It would also be great to see a JSON array example.

Thanks,
-Rich

Santosh Reddy
25th April 2017, 06:03
... No joy here either....

What is the problem? The code looks fine.

Try running this.


QJsonDocument doc;

QJsonObject json;

json.insert("id","070707");
json.insert("request","senddata");
json.insert("datatype","event");
json.insert("eventKey","High Temperature");
json.insert("timestamp", QDateTime::currentDateTime().toTimeSpec(Qt::Offset FromUTC).toString(Qt::ISODate));

doc.setObject(json);

std::cout << doc.toJson(QJsonDocument::Indented).toStdString();

rhb327
25th April 2017, 17:48
I can't seem to get the object within and object part right:
{
...
"eventParameters":{
"Temperature": 25,
"High Temperature": 35,
"Setpoint": 25
}
}

Santosh Reddy
26th April 2017, 06:01
Will look trivial


QDateTime date = QDateTime::currentDateTime().toTimeSpec(Qt::Offset FromUTC);
int temperature = 25;
int highTemperature = 35;
int setpoint = 25;

QJsonObject event;
event["Temperature"] = temperature;
event["High Temperature"] = highTemperature;
event["Setpoint"] = setpoint;

QJsonObject json;
json["id"] = "070707";
json["request"] = "senddata";
json["datatype"] = "event";
json["eventKey"] = "High Temperature";
json["timestamp"] = date.toString(Qt::ISODate);
json["eventParameters"] = event;

QJsonDocument doc;
doc.setObject(json);

std::cout << doc.toJson(QJsonDocument::Indented).toStdString();

rhb327
26th April 2017, 13:28
I see...so a QJsonObject can be assigned to an element of another QJsonObject. Thanks!