Elysia Tools

在一个清晰的工作台里浏览工具、案例、可视化和主题指南。

热门分类

专题

语言
ZHDERUPTENFRES

Elysia Tools

导航

Java

Android Java 序列化示例

Android Java 序列化示例,包括JSON序列化、反序列化和XML解析

案例

这个案例集合中的条目

代码java中等

JSON序列化

使用Gson和其他库将对象转换为JSON字符串

难度

6/10

预计时间

25 min

标签

java, android, json, serialization

前置条件

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", "alice@example.com", 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", "bob@example.com", 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", "alice@example.com", 25, true, new Date()));
        users.add(new User(2, "bob", "bob@example.com", 30, true, new Date()));
        users.add(new User(3, "charlie", "charlie@example.com", 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 ===");
    }
}
代码java中等

JSON反序列化

使用Gson解析JSON字符串并将其转换为对象

难度

6/10

预计时间

25 min

标签

java, android, json, serialization

前置条件

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":"alice@example.com","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\":\"alice@example.com\"}," +
            "{" +
            "\"id\":2,\"username\":\"bob\",\"email\":\"bob@example.com\"}" +
            "]";

        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 ===");
    }
}

工具

经常与该案例搭配使用的工具

相关内容

相关案例集合

相关内容

相关专题

专题

二进制载荷编码、序列化与往返验证

在二进制序列化格式、文本传输编码与转义表示之间转换结构化数据,并通过往返比对确认字段、类型和字节没有被意外改变。

专题

药代动力学教学模型与结果核查

用于教学或 QA 的药代公式、模型假设和结果一致性核查,不提供用药剂量、诊断或临床建议。

专题

JSON 到强类型代码生成器

从 JSON 或 schema 证据生成 TypeScript、Go、Rust、Kotlin、Java、C# 与 Zod 校验模型。

专题

经典与现代密码工具

在安全的教学或 CTF 场景中比较可逆的经典变换与现代加密,并明确玩具密码不等于安全防护。

首页
工具3212
案例593
可视化471
文件查看器103
专题239
标签333
图像、音频与视频657

图像、音频、视频处理、转换与优化工具

数学、日期与金融647

计算器、数值计算、日期逻辑、统计与金融工具

设计与颜色298

颜色、版式、图形、视觉样式与设计辅助工具

文本与写作209

写作、清洗、格式化、提取与文本分析工具

开发与 Web193

开发者工具、网络处理、Web 调试与自动化辅助工具

转换与编码175

格式、文件、压缩包、单位与编码转换工具

潜客测验发布与联系人交接
讣告、悼词与纪念卡的家属复核及交付
本地习惯记录的备份、恢复演练与分享前检查
长文改编 X 串文与 LinkedIn 帖子的事实复核与交付
Markdown 互动课件审校、离线演示与交付

© 2026 Elysia Tools. 保留所有权利。

文档价格关于我们服务条款隐私政策Cookie 政策联系我们

Format Conversion

JSON转XML转换器

将JSON数据转换为XML格式,支持自定义格式化选项

Development

游戏存档查看器

拖入任意游戏存档——Minecraft NBT、虚幻引擎 GVAS、幻兽帕鲁容器、JSON/XML/INI/Lua 文本存档、SQLite 档案——识别格式、引擎版本、关键进度字段并给出有界的结构树。

Development

SBOM SPDX / CycloneDX 许可证策略审计器

审计 SPDX 2.3 或 CycloneDX 1.5 组件许可证,输出 SARIF 和失败依赖链

Format Conversion

XML转JSON转换器

将XML数据转换为JSON格式,支持自定义解析选项

Format Conversion

XLSX 迷你图注入器

通过修改工作表 XML 向 Excel 单元格中插入 Sparkline 迷你图

Development

JSON 转 Java 类

将 JSON 数据转换为 Java class,含 Jackson @JsonProperty 注解、私有字段及 getter/setter

Data Processing

AI数据规范化器

AI驱动的数据格式规范化工具,使用高级AI分析智能清理和标准化混乱数据

Data Processing

数据规范化器

基于代码逻辑的数据格式规范化工具,使用程序化方法清理和标准化混乱数据

Kotlin

Android Kotlin 序列化示例

Android Kotlin 序列化示例,包括JSON序列化、反序列化和XML解析

Objective-C

macOS Objective-C 序列化示例

macOS Objective-C 序列化示例,包括JSON序列化、JSON反序列化和XML解析

Python

Web Python 数据序列化示例

Web Python 数据序列化示例,包括JSON和XML处理

C++

Windows C++ 序列化示例

Windows C++ 数据序列化示例,包括JSON序列化/反序列化和XML解析

Go

Web Go 数据序列化示例

Web Go 数据序列化示例,包括JSON编码/解码和XML解析

Rust

Web Rust 数据序列化示例

Web Rust 数据序列化示例,包括JSON序列化、反序列化和XML解析