0

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

andrewJames
  • 19,570
  • 8
  • 19
  • 51
  • Welcome to Stack Overflow. Please do not post screenshots of your code. Please include the code directly in your question, as formatted text. – andrewJames Jun 15 '20 at 01:49

2 Answers2

1

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);
}
Hababa
  • 551
  • 5
  • 8
0

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.
JackHuynh
  • 74
  • 5