In this video it shows the steps to fix the error – ‘org.json.JSONException’ exception Expected literal value at character 65 of …
In this demonstration it first reproduces the issue by introducing an erroneous comma (,) at the end of the JSON string and then shows the fix by removing it.
I hope you like this video. For any questions, suggestions or appreciation please contact us at: https://programmerworld.co/contact/ or email at: programmerworld1990@gmail.com
Complete source code and other details:
package com.programmerworld.jsonexceptionerrorapp;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.TextView;
import org.json.JSONException;
import org.json.JSONObject;
public class MainActivity extends AppCompatActivity {
private String stringJSON = "{\n" +
" \"fruit\": \"Apple\",\n" +
" \"size\": \"Large\",\n" +
" \"color\": \"Red\"\n" +
"}";
private TextView textView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textView = findViewById(R.id.textView);
}
public void buttonReadJSON(View view){
try {
JSONObject jsonObject = new JSONObject(stringJSON);
textView.setText(jsonObject.getString("fruit"));
} catch (JSONException e) {
textView.setText(e.toString());
}
}
}
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<TextView
android:id="@+id/textView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello World!"
android:textSize="24sp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.498"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.19" />
<Button
android:id="@+id/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="144dp"
android:layout_marginTop="32dp"
android:onClick="buttonReadJSON"
android:text="Read JSON"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>
Screenshots:
Error:
Corrected:
Sample JSON:
{
"fruit": "Apple",
"size": "Large",
"color": "Red"
}