convert QJsonValue to Int



  • I got a (for me) strange behaviour with Json Objects.
    When i try to read a json value and convert it to Int with toInt() i always get the default value (0 if not specified with toInt() method) instead of the read value.
    here is a small example:

    //assume jobj is a QJsonObject andcontains {"ID":"680","auditarea":"General","auditdate":"2015-12-23"}
    qDebug() << jobj.value("ID").toInt(); //always returns default value
    qDebug() << jobj.value("ID").toString().toInt(); // returns 680
    

    Is there something I do wrong here?

    Thanks for some hints.


  • Lifetime Qt Champion

    Hi,

    ID doesn't contain a number but a number in a string hence the need for both conversions. If you wanted to send a number for ID, then you JSON is wrong.


  • Moderators

    To clarify @SGaist's point, see the difference between the 2 objects below:

        "ObjWithString": {
            "ID": "680" 
        },
        "ObjWithInt": {
            "ID": 680
        }
    
    


  • @SGaist, @JKSH

    Thanks for clarification. As i get this JSON from a webservice (not coded by me) i will have to use the "hard" way of JSON Value -> String -> Int to get an integer value


Log in to reply
 

Looks like your connection to Qt Forum was lost, please wait while we try to reconnect.