🎯 Recommended Samples
Balanced sample collections from various categories for you to explore
Android Serialization Java Samples
Android Java serialization examples including JSON serialization, deserialization, and XML parsing
💻 JSON Serialization java
🟡 intermediate
⭐⭐⭐
Convert objects to JSON strings using Gson and other libraries
⏱️ 25 min
🏷️ java, android, json, serialization
Prerequisites:
Intermediate Java, Gson library
// 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
public 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 ===");
}
}
💻 JSON Deserialization java
🟡 intermediate
⭐⭐⭐
Parse JSON strings and convert them to objects using Gson
⏱️ 25 min
🏷️ java, android, json, serialization
Prerequisites:
Intermediate Java, Gson library
// 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
public 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 ===");
}
}