
How to parse JSON without using Gson
You might want to avoid external libraries to keep your APK size small or because your project requirements forbid third-party dependencies. When you try to access data from a JSON string without a parser, you usually end up with manual string manipulation that fails when the format changes.
// The common error when manually splitting strings instead of parsing
java.lang.StringIndexOutOfBoundsException: length=50; regionStart=0; regionLength=-1
at java.lang.String.substring(String.java:1931)This happens because manual parsing doesn't account for escaped characters, whitespace variations, or nested objects. Android provides a native solution through the org.json package, which is included in the SDK by default.
Using JSONObject and JSONArray
The standard way to handle JSON in Android without Gson is using JSONObject for key-value pairs and JSONArray for lists. These classes are straightforward but require you to handle JSONException explicitly. Unlike Gson, which uses reflection to map fields to objects, you must manually pull every value by its key name.
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.List;
public class JsonParser {
public static void main(String[] args) {
String jsonInput = "{\"id\": 101, \"name\": \"Main Store\", \"active\": true, \"tags\": [\"retail\", \"tech\"], \"location\": {\"lat\": 40.7, \"lng\": -74.0}}";
try {
JSONObject root = new JSONObject(jsonInput);
// Basic types
int id = root.getInt("id");
String name = root.getString("name");
boolean isActive = root.getBoolean("active");
// Nested object
JSONObject location = root.getJSONObject("location");
double lat = location.getDouble("lat");
// Array of strings
JSONArray tagsArray = root.getJSONArray("tags");
List<String> tags = new ArrayList<>();
for (int i = 0; i < tagsArray.length(); i++) {
tags.add(tagsArray.getString(i));
}
System.out.println("ID: " + id);
System.out.println("Name: " + name);
System.out.println("Active: " + isActive);
System.out.println("Latitude: " + lat);
System.out.println("Tags: " + tags);
} catch (JSONException e) {
e.printStackTrace();
}
}
}
/*
Expected Output:
ID: 101
Name: Main Store
Active: true
Latitude: 40.7
Tags: [retail, tech]
*/Handling missing keys and nulls
A frequent mistake I see is using get() methods when a key might be missing. If getString("key") is called and the key does not exist, the code throws a JSONException and crashes your app logic. To avoid this, use opt() methods like optString() or optInt(). These return a default value (like an empty string or 0) instead of throwing an exception.
// This will crash if "description" is missing
String desc = root.getString("description");
// This is safer; it returns an empty string if "description" is missing
String safeDesc = root.optString("description");
// You can also provide your own default
String customDefault = root.optString("status", "unknown");I usually prefer optString() for optional fields in an API response. It prevents the need for multiple try-catch blocks or complex if-statements. Remember that JSONObject does not handle nested generics or complex POJO mapping automatically. If you have a deeply nested structure, you will need to write a helper method to iterate through the objects and manually instantiate your Java or Kotlin classes.
One realistic mistake is forgetting that JSONObject.NULL is not the same as a Java null. When checking if a field is explicitly set to null in the JSON, you should use root.isNull("key") rather than comparing the result of get() to null.
Posted in: Android






Comments 0
No comments yet. Be the first to comment.