简体   繁体   中英

How to convert from QString to JSON in C++ side

In qml,

templist:
[{"product_code":"111111111","product_name":"AAAA"},
{"product_code":"222222222","product_name":"BBBB"},
{"product_code":"33333333","product_name":"CCCC"}]

with the help of below code in the qml side, the above templist sent to c++ side as a Qstring,

function listToString() {
    var data = []
    for (var i = 0; i < templist.count; ++i) {
        data.push(templist.get(i))
    }
    var keysList = JSON.stringify(data)
    console.log(keysList)
    **Option A:**  backend.request_add(keysList)
    **Option B:**  backend.request_add(data)
}

in the C++ side,

Option A: keysList as multidata
Option B: data as multidata

I got the above input converted into a

QByteArray br = multidata.toUtf8();

Option A

br = 
[{\"product_code\":\"111111111\",\"product_name\":\"AAAA\"},
{\"product_code\":\"222222222\",\"product_name\":\"BBBB\"},
{\"product_code\":\"33333333\",\"product_name\":\"CCCC\"}]

Option B

br = "QObject(0x560034863a60),QObject(0x5600348628b0),QObject(0x7f76000074d0)"

Question: In Option A, I have converted the key pair to json format before sending it to c++ side as a qstring. is there a way to get the key-pair from Option B directly from this output

br = "QObject(0x560034863a60),QObject(0x5600348628b0),QObject(0x7f76000074d0)"

if I convert in the qml side itself I get the desired answer listed in Option A

br = [{"product_code":"111111111","product_name":"AAAA"},
{"product_code":"222222222","product_name":"BBBB"},
{"product_code":"33333333","product_name":"CCCC"}]

I'm trying to achieve the same desired output using Option B. Please point me in the right direction

Option B will never work. You convert an object instance into a stringified version. This is basically the type (QObject) and its adresse (0x560034863a60).

You have to stringify the JSON data with JSON.stringify(data) to be able to transfer the data as JSON string to the C++ side.

What would be the advantage of Option B anyway?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM