简体   繁体   中英

How can I retrieve qrcode data from an object?

I have a method that can return QRcode data in {'p':1,"x":10,"y":20} this format and it is captured in a variable called qrdata (which is a String data type ).

My question is how can I retrieve value from that key, value pair object?
if.... String qrdata = readQR(image) then how can I retrieve data from qrdata ?

You can do the following:

JSONObject jsonObject = new JSONObject(qrData);

System.out.println("p: " + jsonObject.getInt("p"));
System.out.println("x: " + jsonObject.getInt("x"));
System.out.println("y: " + jsonObject.getInt("y"));

Output:

p: 1
x: 10
y: 20

You can use the JSONObject class from javax.json as mentioned in BuildSlayer's answer.

In the example in your question you use simple quotes for 'p'. Assuming it is not a typo and you meant that different charcacters can be used as quotes, you could run into trouble using it though. In that case, you could use plain java to parse your qrData String:

public String[] parseJSON(String qrData){
    String[] output = new String[qrData.length()];
    int i = 0;
    for (String keyValuePair:qrData.split(",")) {
        output[i++] = keyValuePair.split(":")[1];
    }
    return output;
}

}

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