Complete Guide to JSON String Parsing in Java: From Error Fixing to Best Practices

Nov 16, 2025 · Programming · 33 views · 7.8

Keywords: Java JSON Parsing | org.json Library | JSONArray Processing | Error Fixing | Best Practices

Abstract: This article provides an in-depth exploration of JSON string parsing techniques in Java, based on high-scoring Stack Overflow answers. It thoroughly analyzes common error causes and solutions, starting with the root causes of RuntimeException: Stub! errors and addressing JSON syntax issues and data structure misunderstandings. Through comprehensive code examples, it demonstrates proper usage of the org.json library for parsing JSON arrays, while comparing different parsing approaches including javax.json, Jackson, and Gson, offering performance optimization advice and modern development best practices.

JSON Parsing Error Analysis and Fixes

JSON data parsing is a common task in Java development, but beginners often encounter various errors. Based on high-scoring Stack Overflow answers, let's analyze a typical parsing error case.

Deep Analysis of Error Causes

The original code's java.lang.RuntimeException: Stub! error typically occurs in Android development environments. This happens because the Android SDK's android.jar contains only stub classes needed for compilation, not complete runtime implementations. When running this code in standard Java environments, stub exceptions are triggered.

The solution is to include the complete org.json library in your project. This can be added via Maven dependency:

<dependency>
    <groupId>org.json</groupId>
    <artifactId>json</artifactId>
    <version>20231013</version>
</dependency>

JSON Syntax Structure Correction

The original JSON string had two key issues: extra closing braces and misunderstanding of data structure. The correct JSON should be:

private final static String JSON_DATA =
    "{"
  + "  \"geodata\": ["
  + "    {"
  + "      \"id\": \"1\","
  + "      \"name\": \"Julie Sherman\","                  
  + "      \"gender\" : \"female\","
  + "      \"latitude\" : \"37.33774833333334\","
  + "      \"longitude\" : \"-121.88670166666667\""
  + "    },"
  + "    {"
  + "      \"id\": \"2\","
  + "      \"name\": \"Johnny Depp\","          
  + "      \"gender\" : \"male\","
  + "      \"latitude\" : \"37.336453\","
  + "      \"longitude\" : \"-121.884985\""
  + "    }"
  + "  ]"
  + "}";

Correct Parsing Implementation

The key improvement is recognizing that geodata is a JSON array rather than a single object. The correct parsing code should use JSONArray:

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

public class ShowActivity {
    
    private final static String JSON_DATA = // Use the corrected JSON string
    
    public static void main(final String[] argv) throws JSONException {
        final JSONObject obj = new JSONObject(JSON_DATA);
        final JSONArray geodata = obj.getJSONArray(\"geodata\");
        final int n = geodata.length();
        
        for (int i = 0; i < n; ++i) {
            final JSONObject person = geodata.getJSONObject(i);
            System.out.println(person.getInt(\"id\"));
            System.out.println(person.getString(\"name\"));
            System.out.println(person.getString(\"gender\"));
            System.out.println(person.getDouble(\"latitude\"));
            System.out.println(person.getDouble(\"longitude\"));
        }
    }
}

Data Type Optimization

In the corrected code, we use more appropriate data type methods:

This type matching not only improves code accuracy but also prevents subsequent type conversion errors.

Standard Java JSON Parsing Solutions

Beyond the org.json library, Java standard library also provides JSON parsing capabilities. Using javax.json (or the newer jakarta.json) can be implemented as follows:

import javax.json.Json;
import javax.json.JsonArray;
import javax.json.JsonObject;
import javax.json.JsonReader;
import java.io.StringReader;

public class StandardJsonParser {
    public static void main(String[] args) {
        String jsonString = JSON_DATA; // Use the same JSON data
        
        JsonReader reader = Json.createReader(new StringReader(jsonString));
        JsonObject jsonObject = reader.readObject();
        JsonArray geodata = jsonObject.getJsonArray(\"geodata\");
        
        for (JsonObject person : geodata.getValuesAs(JsonObject.class)) {
            System.out.println(person.getInt(\"id\"));
            System.out.println(person.getString(\"name\"));
            System.out.println(person.getString(\"gender\"));
            System.out.println(person.getJsonNumber(\"latitude\").doubleValue());
            System.out.println(person.getJsonNumber(\"longitude\").doubleValue());
        }
        reader.close();
    }
}

Modern JSON Libraries Comparison

In modern Java development, Jackson and Gson are more popular choices, offering better performance and cleaner APIs.

Jackson Example

import com.fasterxml.jackson.databind.ObjectMapper;
import java.util.List;

class Person {
    private int id;
    private String name;
    private String gender;
    private double latitude;
    private double longitude;
    
    // getters and setters
}

class GeoData {
    private List<Person> geodata;
    
    // getters and setters
}

public class JacksonParser {
    public static void main(String[] args) throws Exception {
        ObjectMapper mapper = new ObjectMapper();
        GeoData geoData = mapper.readValue(JSON_DATA, GeoData.class);
        
        for (Person person : geoData.getGeodata()) {
            System.out.println(person.getId());
            System.out.println(person.getName());
            System.out.println(person.getGender());
            System.out.println(person.getLatitude());
            System.out.println(person.getLongitude());
        }
    }
}

Gson Example

import com.google.gson.Gson;

public class GsonParser {
    public static void main(String[] args) {
        Gson gson = new Gson();
        GeoData geoData = gson.fromJson(JSON_DATA, GeoData.class);
        
        for (Person person : geoData.getGeodata()) {
            System.out.println(person.getId());
            System.out.println(person.getName());
            System.out.println(person.getGender());
            System.out.println(person.getLatitude());
            System.out.println(person.getLongitude());
        }
    }
}

Performance and Selection Recommendations

Different JSON parsing solutions have their own advantages and disadvantages:

Error Handling Best Practices

In actual development, appropriate error handling should be added:

public static void safeJsonParsing(String jsonString) {
    try {
        JSONObject obj = new JSONObject(jsonString);
        if (obj.has(\"geodata\")) {
            JSONArray geodata = obj.getJSONArray(\"geodata\");
            for (int i = 0; i < geodata.length(); i++) {
                JSONObject person = geodata.optJSONObject(i);
                if (person != null) {
                    // Safely get each field
                    int id = person.optInt(\"id\", -1);
                    String name = person.optString(\"name\", \"Unknown\");
                    // ... other fields
                }
            }
        }
    } catch (JSONException e) {
        System.err.println(\"JSON parsing error: \" + e.getMessage());
    }
}

Summary and Recommendations

Through this complete JSON parsing guide, we not only solved specific runtime errors but also deeply understood JSON data structures, selection criteria for different parsing libraries, and best practices for error handling. In actual projects, we recommend:

  1. Choose the appropriate JSON library based on project requirements
  2. Always validate the completeness and correctness of JSON data
  3. Use appropriate data type methods to avoid type conversion errors
  4. Add comprehensive error handling mechanisms
  5. For new projects, prioritize modern libraries like Jackson or Gson

Mastering this knowledge will help developers handle JSON data more efficiently and securely, avoiding common pitfalls and errors.

Copyright Notice: All rights in this article are reserved by the operators of DevGex. Reasonable sharing and citation are welcome; any reproduction, excerpting, or re-publication without prior permission is prohibited.