Elysia Tools

Parcourez outils, exemples, explications visuelles et guides thématiques dans un espace clair.

Catégories populaires

Dossiers

Langue
ZHESPTRUFRDEEN

Elysia Tools

Navigation mobile

Java

Exemples de Sérialisation Android Java

Exemples de sérialisation Android Java incluant sérialisation JSON, désérialisation et analyse XML

Exemples

Entrées de cette collection

Code sourcejavaIntermédiaire

Sérialisation JSON

Convertir les objets en chaînes JSON en utilisant Gson et autres bibliothèques

Difficulté

6/10

Temps estimé

25 min

Étiquettes

java, android, json, serialization

Prérequis

Intermediate Java, Gson library

java
// Android Java JSON Serialization Examples
// Using Gson library and JSONObject

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.reflect.TypeToken;
import com.google.gson.ExclusionStrategy;
import com.google.gson.FieldAttributes;
import org.json.JSONObject;
import org.json.JSONArray;
import org.json.JSONException;
import java.lang.reflect.Type;
import java.util.Date;
import java.util.List;
import java.util.Map;

// Data model classes
class User {
    public int id;
    public String username;
    public String email;
    public Integer age;
    public boolean isActive;
    public Date createdAt;

    public User() {}

    public User(int id, String username, String email, Integer age, boolean isActive, Date createdAt) {
        this.id = id;
        this.username = username;
        this.email = email;
        this.age = age;
        this.isActive = isActive;
        this.createdAt = createdAt;
    }
}

class Product {
    public String productId;
    public String name;
    public double price;
    public List<String> tags;
    public boolean inStock;

    public Product() {}

    public Product(String productId, String name, double price, List<String> tags, boolean inStock) {
        this.productId = productId;
        this.name = name;
        this.price = price;
        this.tags = tags;
        this.inStock = inStock;
    }
}

class Order {
    public int orderId;
    public User user;
    public List<Product> products;
    public double totalAmount;
    public String orderDate;

    public Order() {}

    public Order(int orderId, User user, List<Product> products, double totalAmount, String orderDate) {
        this.orderId = orderId;
        this.user = user;
        this.products = products;
        this.totalAmount = totalAmount;
        this.orderDate = orderDate;
    }
}

// 1. Basic JSON Serialization with Gson
class BasicJsonSerializer {
    private Gson gson = new Gson();

    // Serialize simple object
    public String serializeObject(Object obj) {
        String json = gson.toJson(obj);
        System.out.println("Serialized: " + json);
        return json;
    }

    // Serialize with pretty printing
    public String serializeObjectPretty(Object obj) {
        Gson prettyGson = new GsonBuilder()
            .setPrettyPrinting()
            .create();

        String json = prettyGson.toJson(obj);
        System.out.println("Serialized (pretty):\n" + json);
        return json;
    }

    // Serialize null values explicitly
    public String serializeWithNulls(Object obj) {
        Gson gsonWithNulls = new GsonBuilder()
            .serializeNulls()
            .create();

        return gsonWithNulls.toJson(obj);
    }

    // Serialize date in custom format
    public String serializeWithDateFormat(Object obj, String dateFormat) {
        Gson gsonWithDateFormat = new GsonBuilder()
            .setDateFormat(dateFormat)
            .create();

        return gsonWithDateFormat.toJson(obj);
    }

    // Serialize with custom field naming
    public String serializeWithFieldNaming(Object obj) {
        Gson gsonWithLowercase = new GsonBuilder()
            .setFieldNamingPolicy(com.google.gson.FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES)
            .create();

        return gsonWithLowercase.toJson(obj);
    }
}

// 2. Serialization with JSONObject
class JSONObjectSerializer {

    // Serialize simple object to JSONObject
    public JSONObject serializeToJsonObject(User user) {
        try {
            JSONObject json = new JSONObject();
            json.put("id", user.id);
            json.put("username", user.username);
            json.put("email", user.email);
            json.put("age", user.age);
            json.put("isActive", user.isActive);
            if (user.createdAt != null) {
                json.put("createdAt", user.createdAt.getTime());
            }
            return json;
        } catch (JSONException e) {
            System.out.println("JSON error: " + e.getMessage());
            return null;
        }
    }

    // Serialize to JSON string
    public String serializeToString(User user) {
        JSONObject json = serializeToJsonObject(user);
        return json != null ? json.toString() : null;
    }

    // Serialize list to JSONArray
    public JSONArray serializeList(List<User> users) {
        JSONArray array = new JSONArray();
        for (User user : users) {
            try {
                JSONObject json = new JSONObject();
                json.put("id", user.id);
                json.put("username", user.username);
                json.put("email", user.email);
                array.put(json);
            } catch (JSONException e) {
                System.out.println("Error: " + e.getMessage());
            }
        }
        return array;
    }
}

// 3. Advanced JSON Serialization
class AdvancedJsonSerializer {

    // Serialize with exclusion strategy
    public String serializeWithExclusion(Object obj) {
        Gson gson = new GsonBuilder()
            .setExclusionStrategies(new ExclusionStrategy() {
                @Override
                public boolean shouldSkipField(FieldAttributes field) {
                    // Skip transient fields
                    return java.lang.reflect.Modifier.isTransient(field.getDeclaringClass());
                }

                @Override
                public boolean shouldSkipClass(Class<?> clazz) {
                    return false;
                }
            })
            .create();

        return gson.toJson(obj);
    }

    // Serialize to file
    public boolean serializeToFile(Object obj, String filePath) {
        try {
            Gson gson = new Gson();
            String json = gson.toJson(obj);

            java.io.FileWriter writer = new java.io.FileWriter(filePath);
            writer.write(json);
            writer.close();

            System.out.println("Serialized to file: " + filePath);
            return true;
        } catch (Exception e) {
            System.out.println("Error serializing to file: " + e.getMessage());
            return false;
        }
    }

    // Serialize with versioning
    public String serializeWithVersion(Object obj, double version) {
        Gson gson = new GsonBuilder()
            .setVersion(version)
            .create();

        return gson.toJson(obj);
    }

    // Serialize HTML-safe
    public String serializeHtmlSafe(Object obj) {
        Gson gson = new GsonBuilder()
            .disableHtmlEscaping()
            .create();

        return gson.toJson(obj);
    }
}

// 4. Collection Serialization
class CollectionSerializer {
    private Gson gson = new Gson();

    // Serialize list
    public String serializeList(List<Object> list) {
        return gson.toJson(list);
    }

    // Serialize map
    public String serializeMap(Map<String, Object> map) {
        return gson.toJson(map);
    }

    // Serialize set
    public String serializeSet(java.util.Set<Object> set) {
        return gson.toJson(set);
    }

    // Serialize nested collections
    public String serializeNested(Map<String, List<Object>> data) {
        return gson.toJson(data);
    }

    // Serialize array
    public String serializeArray(Object[] array) {
        return gson.toJson(array);
    }

    // Serialize list with TypeToken
    public String serializeTypedList(List<User> users) {
        Type userListType = new TypeToken<List<User>>() {}.getType();
        return gson.toJson(users, userListType);
    }
}

// 5. Streaming JSON Serialization
class StreamingJsonSerializer {

    // Serialize using JsonWriter (for large datasets)
    public boolean serializeUsingJsonWriter(List<User> data, String filePath) {
        try {
            java.io.FileWriter writer = new java.io.FileWriter(filePath);
            com.google.gson.stream.JsonWriter jsonWriter = new com.google.gson.stream.JsonWriter(writer);

            jsonWriter.beginArray();
            for (User user : data) {
                jsonWriter.beginObject();

                jsonWriter.name("id").value(user.id);
                jsonWriter.name("username").value(user.username);
                jsonWriter.name("email").value(user.email);
                if (user.age != null) {
                    jsonWriter.name("age").value(user.age);
                }
                jsonWriter.name("isActive").value(user.isActive);

                jsonWriter.endObject();
            }
            jsonWriter.endArray();

            jsonWriter.close();
            writer.close();

            System.out.println("Streamed " + data.size() + " items to " + filePath);
            return true;
        } catch (Exception e) {
            System.out.println("Error streaming JSON: " + e.getMessage());
            return false;
        }
    }

    // Serialize with buffering
    public List<String> serializeWithBuffer(List<Object> data, int bufferSize) {
        List<String> chunks = new java.util.ArrayList<>();
        Gson gson = new Gson();

        for (int i = 0; i < data.size(); i += bufferSize) {
            int end = Math.min(i + bufferSize, data.size());
            List<Object> chunk = data.subList(i, end);
            chunks.add(gson.toJson(chunk));
        }

        return chunks;
    }
}

// 6. Android JSONObject (Built-in)
class BuiltInJsonSerializer {

    // Using Android's built-in JSONObject
    public String serializeWithBuiltIn(User user) {
        try {
            JSONObject json = new JSONObject();
            json.put("id", user.id);
            json.put("username", user.username);
            json.put("email", user.email);
            json.put("age", user.age);
            json.put("isActive", user.isActive);

            return json.toString();
        } catch (JSONException e) {
            System.out.println("JSON error: " + e.getMessage());
            return null;
        }
    }

    // Serialize collection
    public String serializeCollection(List<User> users) {
        try {
            JSONArray array = new JSONArray();
            for (User user : users) {
                JSONObject json = new JSONObject();
                json.put("id", user.id);
                json.put("username", user.username);
                json.put("email", user.email);
                array.put(json);
            }
            return array.toString();
        } catch (JSONException e) {
            System.out.println("Error: " + e.getMessage());
            return null;
        }
    }

    // Serialize map
    public String serializeMap(Map<String, Object> data) {
        try {
            JSONObject json = new JSONObject();
            for (Map.Entry<String, Object> entry : data.entrySet()) {
                json.put(entry.getKey(), entry.getValue());
            }
            return json.toString();
        } catch (JSONException e) {
            System.out.println("Error: " + e.getMessage());
            return null;
        }
    }
}

// Main demonstration
class JsonSerializationDemo {
    public static void demonstrateJsonSerialization() {
        System.out.println("=== Android Java JSON Serialization Examples ===\n");

        // 1. Basic serialization
        System.out.println("--- 1. Basic Serialization ---");
        BasicJsonSerializer basicSerializer = new BasicJsonSerializer();

        User user = new User(1, "alice", "[email protected]", 25, true, new Date());

        String json1 = basicSerializer.serializeObject(user);
        System.out.println("Simple: " + json1);

        // 2. Pretty printing
        System.out.println("\n--- 2. Pretty Printing ---");
        String json2 = basicSerializer.serializeObjectPretty(user);

        // 3. Serialization with nulls
        System.out.println("\n--- 3. Serialize with Nulls ---");
        User userWithNulls = new User(2, "bob", "[email protected]", null, true, null);
        String json3 = basicSerializer.serializeWithNulls(userWithNulls);
        System.out.println("With nulls: " + json3);

        // 4. Date formatting
        System.out.println("\n--- 4. Date Formatting ---");
        String json4 = basicSerializer.serializeWithDateFormat(user, "yyyy-MM-dd HH:mm:ss");
        System.out.println("Custom date format: " + json4);

        // 5. Complex object
        System.out.println("\n--- 5. Complex Object Serialization ---");
        List<Product> products = new java.util.ArrayList<>();
        products.add(new Product("P001", "Laptop", 999.99,
            new java.util.ArrayList<>(java.util.Arrays.asList("Electronics", "Computers")), true));
        products.add(new Product("P002", "Mouse", 29.99,
            new java.util.ArrayList<>(java.util.Arrays.asList("Electronics", "Accessories")), true));

        Order order = new Order(1001, user, products, 1029.98, "2025-12-28");
        String json5 = basicSerializer.serializeObjectPretty(order);
        System.out.println("Order:\n" + json5);

        // 6. Collections
        System.out.println("\n--- 6. Collection Serialization ---");
        CollectionSerializer collectionSerializer = new CollectionSerializer();

        List<User> users = new java.util.ArrayList<>();
        users.add(new User(1, "alice", "[email protected]", 25, true, new Date()));
        users.add(new User(2, "bob", "[email protected]", 30, true, new Date()));
        users.add(new User(3, "charlie", "[email protected]", 28, true, new Date()));

        String usersJson = collectionSerializer.serializeTypedList(users);
        System.out.println("Users list: " + usersJson);

        // 7. Field naming policy
        System.out.println("\n--- 7. Field Naming Policy ---");
        String json6 = basicSerializer.serializeWithFieldNaming(user);
        System.out.println("Lowercase with underscores: " + json6);

        // 8. Built-in JSONObject
        System.out.println("\n--- 8. Built-in JSONObject ---");
        BuiltInJsonSerializer builtInSerializer = new BuiltInJsonSerializer();
        String builtInJson = builtInSerializer.serializeWithBuiltIn(user);
        System.out.println("Built-in: " + builtInJson);

        System.out.println("\n=== All JSON Serialization Examples Completed ===");
    }
}
Code sourcejavaIntermédiaire

Désérialisation JSON

Analyser les chaînes JSON et les convertir en objets en utilisant Gson

Difficulté

6/10

Temps estimé

25 min

Étiquettes

java, android, json, serialization

Prérequis

Intermediate Java, Gson library

java
// Android Java JSON Deserialization Examples
// Using Gson library for parsing JSON

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.reflect.TypeToken;
import com.google.gson.JsonSyntaxException;
import org.json.JSONObject;
import org.json.JSONArray;
import org.json.JSONException;
import java.lang.reflect.Type;
import java.util.List;
import java.util.Map;

// Data model classes
class User {
    public int id;
    public String username;
    public String email;
    public Integer age;
    public boolean isActive;
    public String createdAt;

    public User() {}
}

class Product {
    public String productId;
    public String name;
    public double price;
    public List<String> tags;
    public boolean inStock;

    public Product() {}
}

class Order {
    public int orderId;
    public User user;
    public List<Product> products;
    public double totalAmount;
    public String orderDate;

    public Order() {}
}

// 1. Basic JSON Deserialization
class BasicJsonDeserializer {
    private Gson gson = new Gson();

    // Deserialize simple object
    public User deserializeUser(String json) {
        try {
            User user = gson.fromJson(json, User.class);
            System.out.println("Deserialized: " + user.username);
            return user;
        } catch (JsonSyntaxException e) {
            System.out.println("Parse error: " + e.getMessage());
            return null;
        }
    }

    // Deserialize with custom date format
    public User deserializeWithDateFormat(String json, String dateFormat) {
        Gson gsonWithFormat = new GsonBuilder()
            .setDateFormat(dateFormat)
            .create();

        return gsonWithFormat.fromJson(json, User.class);
    }

    // Deserialize to generic object
    public Object deserializeToObject(String json) {
        return gson.fromJson(json, Object.class);
    }
}

// 2. Collection Deserialization
class CollectionDeserializer {
    private Gson gson = new Gson();

    // Deserialize list
    public List<User> deserializeUserList(String json) {
        Type userListType = new TypeToken<List<User>>() {}.getType();
        return gson.fromJson(json, userListType);
    }

    // Deserialize map
    public Map<String, Object> deserializeToMap(String json) {
        Type mapType = new TypeToken<Map<String, Object>>() {}.getType();
        return gson.fromJson(json, mapType);
    }

    // Deserialize array of objects
    public User[] deserializeUserArray(String json) {
        return gson.fromJson(json, User[].class);
    }

    // Deserialize nested structures
    public Map<String, List<String>> deserializeNestedMap(String json) {
        Type nestedMapType = new TypeToken<Map<String, List<String>>>() {}.getType();
        return gson.fromJson(json, nestedMapType);
    }
}

// 3. Safe Deserialization
class SafeJsonDeserializer {
    private Gson gson = new Gson();

    // Safe parse with error handling
    public User safeDeserializeUser(String json) {
        try {
            return gson.fromJson(json, User.class);
        } catch (JsonSyntaxException e) {
            System.out.println("Deserialization error: " + e.getMessage());
            return null;
        }
    }

    // Parse with default value
    public User deserializeOrDefault(String json, User defaultValue) {
        try {
            return gson.fromJson(json, User.class);
        } catch (JsonSyntaxException e) {
            System.out.println("Using default value");
            return defaultValue;
        }
    }

    // Validate JSON structure
    public boolean isValidJson(String json) {
        try {
            gson.fromJson(json, Object.class);
            return true;
        } catch (JsonSyntaxException e) {
            return false;
        }
    }

    // Safe collection parsing
    public List<User> safeDeserializeList(String json) {
        try {
            Type userListType = new TypeToken<List<User>>() {}.getType();
            return gson.fromJson(json, userListType);
        } catch (JsonSyntaxException e) {
            System.out.println("List parse error: " + e.getMessage());
            return new java.util.ArrayList<>();
        }
    }
}

// 4. Deserialization with JSONObject
class JSONObjectDeserializer {

    // Parse User from JSONObject
    public User parseUser(JSONObject json) {
        User user = new User();
        try {
            user.id = json.getInt("id");
            user.username = json.getString("username");
            user.email = json.getString("email");
            user.age = json.optInt("age");
            user.isActive = json.optBoolean("isActive", true);
            user.createdAt = json.optString("createdAt", null);
        } catch (JSONException e) {
            System.out.println("Parse error: " + e.getMessage());
        }
        return user;
    }

    // Parse from JSON string
    public User parseFromString(String jsonString) {
        try {
            JSONObject json = new JSONObject(jsonString);
            return parseUser(json);
        } catch (JSONException e) {
            System.out.println("Parse error: " + e.getMessage());
            return null;
        }
    }

    // Parse list from JSONArray
    public List<User> parseUserList(JSONArray jsonArray) {
        List<User> users = new java.util.ArrayList<>();
        for (int i = 0; i < jsonArray.length(); i++) {
            try {
                JSONObject json = jsonArray.getJSONObject(i);
                users.add(parseUser(json));
            } catch (JSONException e) {
                System.out.println("Error parsing item " + i + ": " + e.getMessage());
            }
        }
        return users;
    }

    // Parse list from JSON array string
    public List<User> parseUserList(String jsonArrayString) {
        try {
            JSONArray jsonArray = new JSONArray(jsonArrayString);
            return parseUserList(jsonArray);
        } catch (JSONException e) {
            System.out.println("Array parse error: " + e.getMessage());
            return new java.util.ArrayList<>();
        }
    }

    // Parse with fallback values
    public User parseWithFallbacks(String jsonString) {
        try {
            JSONObject json = new JSONObject(jsonString);
            User user = new User();

            user.id = json.optInt("id", 0);
            user.username = json.optString("username", "unknown");
            user.email = json.optString("email", "");
            user.age = json.optInt("age", 0);
            user.isActive = json.optBoolean("isActive", true);

            return user;
        } catch (JSONException e) {
            System.out.println("Fallback parse error: " + e.getMessage());
            return new User();
        }
    }
}

// 5. Partial Deserialization
class PartialJsonDeserializer {

    // Extract specific fields
    public String extractField(String json, String fieldName) {
        try {
            JSONObject jsonObject = new JSONObject(json);
            if (jsonObject.has(fieldName)) {
                return jsonObject.getString(fieldName);
            }
            return null;
        } catch (JSONException e) {
            System.out.println("Extract error: " + e.getMessage());
            return null;
        }
    }

    // Extract multiple fields
    public Map<String, String> extractFields(String json, String[] fieldNames) {
        Map<String, String> result = new java.util.HashMap<>();
        try {
            JSONObject jsonObject = new JSONObject(json);
            for (String fieldName : fieldNames) {
                if (jsonObject.has(fieldName)) {
                    try {
                        result.put(fieldName, jsonObject.getString(fieldName));
                    } catch (JSONException e) {
                        result.put(fieldName, jsonObject.opt(fieldName));
                    }
                }
            }
        } catch (JSONException e) {
            System.out.println("Extract fields error: " + e.getMessage());
        }
        return result;
    }

    // Get JSON array at path
    public List<String> extractArrayAtPath(String json, String arrayField) {
        List<String> result = new java.util.ArrayList<>();
        try {
            JSONObject jsonObject = new JSONObject(json);
            if (jsonObject.has(arrayField)) {
                JSONArray jsonArray = jsonObject.getJSONArray(arrayField);
                for (int i = 0; i < jsonArray.length(); i++) {
                    result.add(jsonArray.getString(i));
                }
            }
        } catch (JSONException e) {
            System.out.println("Array extract error: " + e.getMessage());
        }
        return result;
    }
}

// 6. Streaming JSON Deserialization
class StreamingJsonDeserializer {

    // Parse using JsonReader (for large JSON files)
    public List<User> parseLargeJsonFile(String filePath) {
        List<User> users = new java.util.ArrayList<>();

        try {
            java.io.FileReader reader = new java.io.FileReader(filePath);
            com.google.gson.stream.JsonReader jsonReader = new com.google.gson.stream.JsonReader(reader);

            jsonReader.beginArray();
            while (jsonReader.hasNext()) {
                User user = new User();
                jsonReader.beginObject();

                while (jsonReader.hasNext()) {
                    String name = jsonReader.nextName();
                    switch (name) {
                        case "id":
                            user.id = jsonReader.nextInt();
                            break;
                        case "username":
                            user.username = jsonReader.nextString();
                            break;
                        case "email":
                            user.email = jsonReader.nextString();
                            break;
                        case "age":
                            user.age = jsonReader.nextInt();
                            break;
                        case "isActive":
                            user.isActive = jsonReader.nextBoolean();
                            break;
                        case "createdAt":
                            user.createdAt = jsonReader.nextString();
                            break;
                        default:
                            jsonReader.skipValue();
                    }
                }

                jsonReader.endObject();
                users.add(user);
            }
            jsonReader.endArray();

            jsonReader.close();
            reader.close();
        } catch (Exception e) {
            System.out.println("Streaming parse error: " + e.getMessage());
        }

        return users;
    }
}

// 7. Type Adapters
class CustomTypeAdapterDeserializer {

    // Deserialize with custom type adapter
    public static class DateDeserializer implements com.google.gson.JsonDeserializer<Date> {
        @Override
        public Date deserialize(com.google.gson.JsonElement json, Type typeOfT,
                                com.google.gson.JsonDeserializationContext context) {
            try {
                String dateStr = json.getAsString();
                java.text.SimpleDateFormat formatter = new java.text.SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
                return formatter.parse(dateStr);
            } catch (Exception e) {
                return null;
            }
        }
    }

    // Register and deserialize with custom adapter
    public User deserializeWithCustomAdapter(String json) {
        Gson gson = new GsonBuilder()
            .registerTypeAdapter(Date.class, new DateDeserializer())
            .create();

        return gson.fromJson(json, User.class);
    }
}

// Main demonstration
class JsonDeserializationDemo {
    public static void demonstrateJsonDeserialization() {
        System.out.println("=== Android Java JSON Deserialization Examples ===\n");

        // 1. Basic deserialization
        System.out.println("--- 1. Basic Deserialization ---");
        BasicJsonDeserializer deserializer = new BasicJsonDeserializer();

        String userJson = '{"id":1,"username":"alice","email":"[email protected]","age":25,"isActive":true}';
        User user = deserializer.deserializeUser(userJson);
        System.out.println("User: " + user.username + ", " + user.email);

        // 2. Collection deserialization
        System.out.println("\n--- 2. Collection Deserialization ---");
        CollectionDeserializer collectionDeserializer = new CollectionDeserializer();

        String usersJson = "[{" +
            "\"id\":1,\"username\":\"alice\",\"email\":\"[email protected]\"}," +
            "{" +
            "\"id\":2,\"username\":\"bob\",\"email\":\"[email protected]\"}" +
            "]";

        List<User> users = collectionDeserializer.deserializeUserList(usersJson);
        System.out.println("Users count: " + users.size());

        // 3. Safe deserialization
        System.out.println("\n--- 3. Safe Deserialization ---");
        SafeJsonDeserializer safeDeserializer = new SafeJsonDeserializer();

        String invalidJson = "{invalid json}";
        User parsedUser = safeDeserializer.safeDeserializeUser(invalidJson);
        System.out.println("Parsed with error handling: " + (parsedUser != null ? parsedUser.username : "null"));

        boolean isValid = safeDeserializer.isValidJson(userJson);
        System.out.println("Is valid: " + isValid);

        // 4. JSONObject deserialization
        System.out.println("\n--- 4. JSONObject Deserialization ---");
        JSONObjectDeserializer jsonObjectDeserializer = new JSONObjectDeserializer();

        User userFromObj = jsonObjectDeserializer.parseFromString(userJson);
        System.out.println("Parsed from JSONObject: " + userFromObj.username);

        // 5. Partial deserialization
        System.out.println("\n--- 5. Partial Deserialization ---");
        PartialJsonDeserializer partialDeserializer = new PartialJsonDeserializer();

        String username = partialDeserializer.extractField(userJson, "username");
        System.out.println("Extracted username: " + username);

        String[] fields = {"username", "email", "age"};
        Map<String, String> extracted = partialDeserializer.extractFields(userJson, fields);
        System.out.println("Extracted fields: " + extracted);

        // 6. Complex nested object
        System.out.println("\n--- 6. Complex Nested Object ---");
        String orderJson = "{" +
            "\"orderId\": 1001," +
            "\"user\": " + userJson + "," +
            "\"totalAmount\": 1029.98," +
            "\"orderDate\": \"2025-12-28\"" +
            "}";

        Order order = new Gson().fromJson(orderJson, Order.class);
        System.out.println("Order ID: " + order.orderId);
        System.out.println("User: " + (order.user != null ? order.user.username : "null"));

        System.out.println("\n=== All JSON Deserialization Examples Completed ===");
    }
}

Outils

Outils souvent utilisés avec cet exemple

Associé

Collections d’exemples associées

Associé

Dossiers associés

Dossier

Déduire un JSON Schema depuis des exemples et des tableurs

Produisez un brouillon de JSON Schema relisible à partir d'exemples JSON représentatifs ou de lignes XLSX, puis examinez types, caractère obligatoire, valeurs nulles et anomalies avant toute adoption contractuelle.

Dossier

Revue et livraison d’un module de jeu promotionnel auto-hébergé

Contrôlez configuration, exemples de réponses, lisibilité et affichage adaptatif avant de livrer les fichiers du module et les preuves de recette de son intégration.

Dossier

Generateurs JSON vers code type

Generez des modeles types depuis JSON ou schema pour TypeScript, Go, Rust, Kotlin, Java, C# et la validation Zod.

Dossier

Modeles pharmacocinetiques pedagogiques et controle des resultats

Explorer les formules pharmacocinetiques, les hypotheses de modele et la coherence des resultats pour l'enseignement ou la QA, sans avis clinique.

Accueil
Outils3208
Exemples593
Visualisations469
Visionneuses de fichiers103
Dossiers237
Étiquettes333
Images, audio et vidéo657

Outils de traitement, conversion et optimisation d’images, d’audio et de vidéo

Maths, dates et finance646

Calculateurs, outils numériques, logique de dates, statistiques et finance

Design et couleur298

Outils de couleur, mise en page, graphisme, style visuel et assistance design

Texte et rédaction209

Outils de rédaction, nettoyage, formatage, extraction et analyse de texte

Développement et Web193

Utilitaires développeur, réseau, débogage Web et assistants d’automatisation

Conversion et encodage175

Outils de conversion de formats, fichiers, archives, unités et encodages

Habitudes privées : sauvegarde, restauration et partage vérifié
D’un article aux brouillons X et LinkedIn : revue factuelle et livraison
Revue de cours Markdown interactif et livraison hors ligne
Revue d’aménagement d’une petite pièce et dossier d’emménagement
Examen des sources FLAC/WAV et transmission des preuves

© 2026 Elysia Tools. Tous droits réservés.

DocumentationTarifsÀ proposConditions d'utilisationPolitique de confidentialitéCookiesContact

Format Conversion

Convertisseur JSON vers XML

Convertit les données JSON au format XML avec des options de formatage personnalisables

Development

Visionneuse de sauvegardes de jeu

Déposez n’importe quel fichier de sauvegarde — NBT Minecraft, GVAS Unreal Engine, conteneurs Palworld, saves texte JSON/XML/INI/Lua, profils SQLite — et obtenez le format détecté, les versions du moteur, les champs de progression clés et un arbre structurel borné.

Development

Auditeur de politique de licences SBOM SPDX / CycloneDX

Audite les licences SPDX 2.3 ou CycloneDX 1.5 et produit du SARIF avec chemins de dépendance

Format Conversion

Convertisseur XML vers JSON

Convertit les données XML au format JSON avec des options d'analyse personnalisables

Format Conversion

Injecteur XLSX de Sparklines

Insere des sparklines dans Excel en modifiant le XML de feuille

Development

JSON vers Java Class

Convertit des données JSON en classes Java avec annotations Jackson @JsonProperty, champs privés, getters et setters

Data Processing

Normaliseur de Données IA

Outil de normalisation de données alimenté par IA qui nettoie intelligemment et standardise les données désordonnées

Data Processing

Normaliseur de Données

Outil de normalisation de données basé sur le code qui nettoie et standardise les données désordonnées en utilisant une logique programmatique

Kotlin

Exemples de Sérialisation Android Kotlin

Exemples de sérialisation Android Kotlin incluant la sérialisation JSON, la désérialisation et l'analyse XML

Objective-C

Sérialisation macOS Objective-C - Exemples

Exemples sérialisation macOS Objective-C incluant sérialisation JSON, désérialisation JSON et analyse XML

Python

Exemples de Sérialisation Web Python

Exemples de sérialisation Web Python incluant le traitement JSON et XML

C++

Exemples de Sérialisation Windows C++

Exemples de sérialisation de données Windows C++ incluant la sérialisation/désérialisation JSON et l'analyse XML

Go

Exemples de Sérialisation de Données Web Go

Exemples de sérialisation de données Web Go incluant l'encodage/décodage JSON et l'analyse XML

Rust

Exemples de Sérialisation de Données Web Rust

Exemples de sérialisation de données Web Rust incluant la sérialisation JSON, la désérialisation et l'analyse XML