I have stayed with the problem for more than 3 days of research but cant find any solvable solution. My android project makes a request to my gcloud functions and the function returns a string response with a String format:
[{"response": [{"Commission": 50, "Price": 0.5, "Quantity": "20"}, {"Commission": 50, "Quantity": 20, "Price": 1}, {"Quantity": 20, "Price": 10, "Commission": 50}], "code": 200}]
I was able to convert the string to JSON and retrieve the value of the "response" key.
try {
//convertion of response to json to fetch value
JSONObject jsonObj = new JSONObject("[{"response": [{"Commission": 50, "Price": 0.5, "Quantity": "20"}, {"Commission": 50, "Quantity": 20, "Price": 1}, {"Quantity": 20, "Price": 10, "Commission": 50}], "code": 200}]");
String code = jsonObj.getString("code");
final String Cod = code;
if (Cod.equals("200")){
String availableInv = jsonObj.getString("response");
availableInv = availableInv.replace("[", "");
availableInv = availableInv.replace("]", "");
String strng[] = availableInv.split("},");
for (String val:strng) {
int valLength = val.length();
if(!val.substring(valLength-1, valLength).contentEquals("}")) {
val +="}";
}
System.out.println(">>>>>>=====================response==========="+val);
JSONObject jsonObjInv = new JSONObject(val);
float price = Float.valueOf(jsonObjInv.getString("Price"));
float comission = Float.valueOf(jsonObjInv.getString("Commission"));
float quantity = Float.valueOf(jsonObjInv.getString("Quantity"));
myDataset.add(new InvestmentsModel(price,comission, quantity));
}
}
}
Now i want to be able to iterate through the list of the JSON object and fetch the keys and values. When i run my solution i get the following error:
2020-03-24 16:17:55.235 4959-5006/com.example.SMS E/AndroidRuntime: FATAL EXCEPTION: OkHttp Dispatcher
Process: com.example.SMS, PID: 4959
java.util.regex.PatternSyntaxException: Syntax error in regexp pattern near index 1
},
^
at java.util.regex.Pattern.compileImpl(Native Method)
at java.util.regex.Pattern.compile(Pattern.java:1340)
at java.util.regex.Pattern.<init>(Pattern.java:1324)
at java.util.regex.Pattern.compile(Pattern.java:946)
at java.lang.String.split(String.java:2384)
at java.lang.String.split(String.java:2426)
at com.example.SMS.Fragment.investEarnFrag_1$5.onResponse(investEarnFrag_1.java:251)
at okhttp3.internal.connection.RealCall$AsyncCall.run(RealCall.kt:504)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1162)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:636)
at java.lang.Thread.run(Thread.java:764)