Casting Map to a JSONObject for android app. Builds but crashes on run-time. Looked in the Logcat and got error:
org.json.JSONObject cannot be cast to java.util.Map
Here is the section related:
JSONObject item = new JSONObject(data);
Map product = ((Map)item.get("product"));
It's specifically the second line that's making it crash. I commented out code until un-commenting this line caused the crash.
The JSON it's linked to is here.
Unmapping the JSONObject gives this error:
Incompatible types.
Required: java.util.Map<, >
Found: java.lang.Object
More extensive code view:
TextView parsed = findViewById(R.id.jsonParse);
String barcodeNum = result.getText();
String productName = "";
try {
URL url = new URL("https://world.openfoodfacts.org/api/v0/product/" + barcodeNum + ".json");
HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
InputStream inputStream = httpURLConnection.getInputStream();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
String data = "";
String line = "";
while (line != null){
line = bufferedReader.readLine();
data = data + line;
}
JSONObject item = new JSONObject(data);
final JSONObject product = item.getJSONObject("product");
final Map<String, Object> map =
product.keySet()
.stream()
.collect(Collectors.toMap(
Function.identity(),
product::get
));