0

I'm trying to parse a simple JSON data in Qt5.

Code looks like this :

    ...
    socket->readDatagram(Buffer.data(),Buffer.size(),&sender,&senderPort);

    QJsonParseError jsonError;
    QJsonDocument dataJson = QJsonDocument::fromJson(Buffer.data(),&jsonError);
    if (jsonError.error != QJsonParseError::NoError){
        qDebug() << jsonError.errorString();
    }
    QJsonObject map = dataJson.object();
    //map["x"].toDouble()

But for some reason my map is empty, here is a debugging snap : QJsonDocument to object is empty

How can I resolve this ?

Data :

'{\"x\":1,\"y\":2,\"z\":3}'
p-a-o-l-o
  • 9,807
  • 2
  • 22
  • 35
Maifee Ul Asad
  • 3,992
  • 6
  • 38
  • 86
  • You should see your log print about json error string in application output of Qt Creator because fromJson call clearly doesn't succeed. And if parsing fails you shouldn't continue execution of your function but e.g. return from it. I suspect your json string escaping goes wrong. What if you replace single quotes with double quotes in your echo call? – talamaki Dec 10 '20 at 07:27
  • I've test your piece of code and it worked for me! Make sure that your buffer is full when JSON deserializer start to work. Don't rely on debug outputs, add some console print and check that. – Farshid616 Dec 10 '20 at 07:30

1 Answers1

1

Assuming that you're reading correctly, you should test with a command like this:

echo -n \{\"x\":1,\"y\":2,\"\z\":3\} > /dev/udp/127.0.0.1/8080

So, get rid of single quotes and escape curly brackets.

Even better: put your json data in a myfile file and use cat myfile > /dev/udp/127.0.0.1/8080

p-a-o-l-o
  • 9,807
  • 2
  • 22
  • 35
  • this worked, but can you give me some reason how it worked ? – Maifee Ul Asad Dec 10 '20 at 09:07
  • nothing really wrong in your code, more a bash issue, I think – p-a-o-l-o Dec 10 '20 at 14:20
  • Just one question, why sending data to `192.168.0.108` doesn't work? – Maifee Ul Asad Dec 10 '20 at 14:53
  • It depends on how you bind (and on the address being correct). Try `udpSocket.bind(QHostAddress::Any, 8080);` or `udpSocket.bind(8080);`, which is the same. – p-a-o-l-o Dec 10 '20 at 15:29
  • I've tried `Any`, `AnyIPv4`, hard-coded `192.168.0.108` everything, but doesn't work – Maifee Ul Asad Dec 10 '20 at 15:33
  • I think you can post a new question about that (if you're super sure that the address is correct). Just post the `ip address` output in the question, possibly not as an image :) and maybe post enough code to have a Minimal, Reproducible Example, just to avoid downvotes. – p-a-o-l-o Dec 10 '20 at 15:38
  • actually i did, 5 hours ago : https://stackoverflow.com/questions/65232467/send-data-to-qt-applicationlaptop-from-android-using-udp – Maifee Ul Asad Dec 10 '20 at 15:40
  • Are you reading from the `readyRead` slot? I think you should really post more code. – p-a-o-l-o Dec 10 '20 at 15:45