{{theTime}}

Search This Blog

Total Pageviews

JSONObject Class to parse the JSON data

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

public class JSONParserExample {
    public static void main(String[] args) {
        // Example JSON data
        String jsonData = "{\"name\": \"testname\", \"age\": 30, \"isStudent\": true, \"languages\": [\"Java\", \"Python\"]}";

        try {
            // Parsing JSON data
            JSONObject jsonObject = new JSONObject(jsonData);

            // Accessing individual fields
            String name = jsonObject.getString("name");
            int age = jsonObject.getInt("age");
            boolean isStudent = jsonObject.getBoolean("isStudent");
           
            System.out.println("Name: " + name);
            System.out.println("Age: " + age);
            System.out.println("Is Student: " + isStudent);

            // Parsing an array within JSON
            JSONArray languages = jsonObject.getJSONArray("languages");
            System.out.println("Languages:");
            for (int i = 0; i < languages.length(); i++) {
                System.out.println("- " + languages.getString(i));
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }
}

No comments:

MongoDB Tutorial MongoDB Tutorial Table of Contents Introduction to MongoDB Installation Creating a Database Creati...