Reading data from Android App using bluetooth

I have Java code to receive data in Android App via Bluetooth like the attached code

Java Code

so readMessage will equal = {\"Pin\":\"A4\",\"Value\":\"20\"},{\"Pin\":\"A5\",\"Value\":\"925\"},{\"Pin\":\"A0\",\"Value\":\"30\"}

So I want to take only the values after string \"Value\" from received data so

Can anyone suggest how to make do that? Thanks

Upvotes: 0

Views: 483

Answers (2)

JackHuynh
JackHuynh

Reputation: 74

You can use Gson to convert Json to Object. (https://github.com/google/gson)

  1. Create Model Class
data class PinItem(
           @SerializedName("Pin")
           val pin: String? = null,
           @SerializedName("Value")
           val value: String? = null
       )
  1. Convert your json.
    val json = "[{"Pin":"A4","Value":"20"},{"Pin":"A5","Value":"925"},{"Pin":"A0","Value":"30"}]"

    val result =  Gson().fromJson(this, object : TypeToken<List<PinItem>>() {}.type)
  1. So now you having list PinItem and you can get all info off it.

Upvotes: 0

Hababa
Hababa

Reputation: 571

you can parse the readMessage with JSON format

example:

String[] pinValueArr = readMessage.split(",")
for (String pinValue : pinValueArr) {
    try {
        JSONObject pinValueJSON = new JSONObject(pinValue);
        String pin = pinValueJSON.optString("pin", "");  // opt means if parse failed, return default value what is ""
        int pin = pinValueJSON.optInt("Value", 0);   // opt means if parse failed, return default value what is "0"
    } catch (JSONParsedException e) {
        // catch exception when parse to JSONObject failed
    }
}

And if you want to manage them, you can make a List and add them all.

List<JSONObject> pinValueList = new ArrayList<JSONObject>();
for (String pinValue : pinValueArr) {
    JSONObject pinValueJSON = new JSONObject(pinValue);
    // ..
    pinValueList.add(pinValueJSON);
}

Upvotes: 1

Related Questions