### Integrate MGson into Android Projects Source: https://context7.com/wilson-1024/mgson/llms.txt Guides the integration process via Gradle dependencies and demonstrates how to replace standard Gson instances with MGson in an Android Activity to ensure safe JSON deserialization. ```groovy dependencies { implementation project(':lib-mgson') } ``` ```java import com.chemanman.lib_mgson.MGson; import com.google.gson.Gson; // Inside Activity Gson gson = MGson.newGson(); MyDataModel data = gson.fromJson(jsonResponse, MyDataModel.class); ``` -------------------------------- ### Perform Safe Type Conversions with StringUtils Source: https://context7.com/wilson-1024/mgson/llms.txt Provides utility methods for safely converting strings to numeric types or handling null/empty strings. These methods return default values (like 0 or 0.0) instead of throwing exceptions when parsing fails. ```java import com.chemanman.lib_mgson.util.StringUtils; Integer intVal = StringUtils.toInt("123"); // 123 Integer intVal2 = StringUtils.toInt("abc"); // 0 Double doubleVal = StringUtils.toDouble("3.14"); // 3.14 boolean isEmpty = StringUtils.isEmpty("0"); // true ``` -------------------------------- ### Create Safe Gson Instance with MGson Source: https://context7.com/wilson-1024/mgson/llms.txt The `MGson.newGson()` method provides a pre-configured Gson instance with custom type adapters for robust JSON parsing. It handles String, numeric types, objects, and collections, returning safe default values for mismatched types. ```java import com.chemanman.lib_mgson.MGson; import com.google.gson.Gson; // Create a safe Gson instance Gson gson = MGson.newGson(); // Define data model public class User { public int id; public String name; public int age; public List tags; } // Normal JSON parsing String normalJson = "{\"id\":1,\"name\":\"张三\",\"age\":25,\"tags\":[\"开发者\",\"Android\"]}"; User user = gson.fromJson(normalJson, User.class); // Output: User{id=1, name='张三', age=25, tags=[开发者, Android]} // Handle mismatched JSON (name expects String, gets array; age expects int, gets string; tags expects array, gets object) String mismatchedJson = "{\"id\":1,\"name\":[],\"age\":\"abc\",\"tags\":{}}"; User user2 = gson.fromJson(mismatchedJson, User.class); // With MGson: User{id=1, name='', age=0, tags=[]} // With standard Gson: Throws JsonSyntaxException ``` -------------------------------- ### Safe String Type Parsing with MGson Source: https://context7.com/wilson-1024/mgson/llms.txt MGson's string type adapter handles mismatches where a string is expected but an object, array, or null is received, returning an empty string. Boolean values are converted to their string representations ('true' or 'false'). ```java import com.chemanman.lib_mgson.MGson; import com.google.gson.Gson; public class Product { public String productName; public String description; public String category; } Gson gson = MGson.newGson(); // Scenario 1: String field returns object {} - defaults to empty string String json1 = "{\"productName\":{\"key\":\"value\"},\"description\":\"手机\",\"category\":\"电子产品\"}"; Product product1 = gson.fromJson(json1, Product.class); // Output: Product{productName='', description='手机', category='电子产品'} // Scenario 2: String field returns array [] - defaults to empty string String json2 = "{\"productName\":[1,2,3],\"description\":\"手机\",\"category\":\"电子产品\"}"; Product product2 = gson.fromJson(json2, Product.class); // Output: Product{productName='', description='手机', category='电子产品'} // Scenario 3: String field returns null - defaults to empty string String json3 = "{\"productName\":null,\"description\":null,\"category\":null}"; Product product3 = gson.fromJson(json3, Product.class); // Output: Product{productName='', description='', category=''} // Scenario 4: String field returns boolean - converts to string String json4 = "{\"productName\":true,\"description\":false,\"category\":\"电子产品\"}"; Product product4 = gson.fromJson(json4, Product.class); // Output: Product{productName='true', description='false', category='电子产品'} ``` -------------------------------- ### Parse Complex Nested JSON with MGson Source: https://context7.com/wilson-1024/mgson/llms.txt Demonstrates how to define data models for complex JSON structures and use MGson to safely parse them even when types mismatch (e.g., receiving an array instead of a string). It handles nested objects and keyword conflicts using standard Gson annotations. ```java import com.chemanman.lib_mgson.MGson; import com.google.gson.Gson; import com.google.gson.annotations.SerializedName; public class CoSetting { public int company_id; public String company_name; public OrderData order_data; public CoSettingBean co_setting; @SerializedName("enum") public EnumBean enumX; public String src; } Gson gson = MGson.newGson(); String complexJson = "{\"company_id\":123,\"company_name\":[],\"src\":\"co\"}"; CoSetting setting = gson.fromJson(complexJson, CoSetting.class); ``` -------------------------------- ### Safe Collection Parsing with CollectionTypeAdapterFactory (Java) Source: https://context7.com/wilson-1024/mgson/llms.txt Illustrates how CollectionTypeAdapterFactory handles parsing of collection types like List and Set. If a JSON field expected to be a collection is instead an object, number, string, boolean, or null, it returns an empty collection instance, preventing runtime errors. This is crucial for robust data handling from external sources. ```java import com.chemanman.lib_mgson.MGson; import com.google.gson.Gson; import java.util.List; import java.util.ArrayList; public class UserProfile { public String username; public List hobbies; public List scores; } // Initialize MGson Gson gson = MGson.newGson(); // Scenario 1: Collection field returns an object {} - returns an empty collection String json1 = "{\"username\":\"张三\",\"hobbies\":{\"key\":\"value\"},\"scores\":[90,85,92]}"; UserProfile profile1 = gson.fromJson(json1, UserProfile.class); // Expected Output: UserProfile{username='张三', hobbies=[], scores=[90, 85, 92]} // Scenario 2: Collection field returns a string - returns an empty collection String json2 = "{\"username\":\"张三\",\"hobbies\":\"篮球,足球\",\"scores\":[90,85,92]}"; UserProfile profile2 = gson.fromJson(json2, UserProfile.class); // Expected Output: UserProfile{username='张三', hobbies=[], scores=[90, 85, 92]} // Scenario 3: Collection field returns a number - returns an empty collection String json3 = "{\"username\":\"张三\",\"hobbies\":12345,\"scores\":[90,85,92]}"; UserProfile profile3 = gson.fromJson(json3, UserProfile.class); // Expected Output: UserProfile{username='张三', hobbies=[], scores=[90, 85, 92]} // Scenario 4: Collection field returns null - returns an empty collection String json4 = "{\"username\":\"张三\",\"hobbies\":null,\"scores\":null}"; UserProfile profile4 = gson.fromJson(json4, UserProfile.class); // Expected Output: UserProfile{username='张三', hobbies=[], scores=[]} // Scenario 5: Collection field returns a boolean - returns an empty collection String json5 = "{\"username\":\"张三\",\"hobbies\":true,\"scores\":false}"; UserProfile profile5 = gson.fromJson(json5, UserProfile.class); // Expected Output: UserProfile{username='张三', hobbies=[], scores=[]} // Scenario 6: Normal collection parsing String json6 = "{\"username\":\"张三\",\"hobbies\":[\"篮球\",\"足球\",\"游泳\"],\"scores\":[90,85,92]}"; UserProfile profile6 = gson.fromJson(json6, UserProfile.class); // Expected Output: UserProfile{username='张三', hobbies=[篮球, 足球, 游泳], scores=[90, 85, 92]} ``` -------------------------------- ### Safe Object Parsing with ReflectiveTypeAdapterFactory (Java) Source: https://context7.com/wilson-1024/mgson/llms.txt Demonstrates how ReflectiveTypeAdapterFactory safely parses JSON into Java objects. When a JSON field expected to be an object is instead an array, number, string, boolean, or null, it returns a new, empty instance of the object via its constructor, preventing parsing errors. This is useful for handling inconsistent API responses. ```java import com.chemanman.lib_mgson.MGson; import com.google.gson.Gson; public class Address { public String province; public String city; public String district; } public class Company { public int companyId; public String companyName; public Address address; } // Initialize MGson Gson gson = MGson.newGson(); // Scenario 1: Object field returns an array [] - returns an empty object instance String json1 = "{\"companyId\":123,\"companyName\":\"测试公司\",\"address\":[]}"; Company company1 = gson.fromJson(json1, Company.class); // Expected Output: Company{companyId=123, companyName='测试公司', address=Address{province=null, city=null, district=null}} // Scenario 2: Object field returns a string - returns an empty object instance String json2 = "{\"companyId\":123,\"companyName\":\"测试公司\",\"address\":\"北京市\"}"; Company company2 = gson.fromJson(json2, Company.class); // Expected Output: Company{companyId=123, companyName='测试公司', address=Address{province=null, city=null, district=null}} // Scenario 3: Object field returns a number - returns an empty object instance String json3 = "{\"companyId\":123,\"companyName\":\"测试公司\",\"address\":12345}"; Company company3 = gson.fromJson(json3, Company.class); // Expected Output: Company{companyId=123, companyName='测试公司', address=Address{province=null, city=null, district=null}} // Scenario 4: Object field returns null - returns an empty object instance String json4 = "{\"companyId\":123,\"companyName\":\"测试公司\",\"address\":null}"; Company company4 = gson.fromJson(json4, Company.class); // Expected Output: Company{companyId=123, companyName='测试公司', address=Address{province=null, city=null, district=null}} // Scenario 5: Normal nested object parsing String json5 = "{\"companyId\":123,\"companyName\":\"测试公司\",\"address\":{\"province\":\"北京市\",\"city\":\"北京市\",\"district\":\"朝阳区\"}}"; Company company5 = gson.fromJson(json5, Company.class); // Expected Output: Company{companyId=123, companyName='测试公司', address=Address{province='北京市', city='北京市', district='朝阳区'}} ``` -------------------------------- ### Safe Numeric Type Parsing with MGson Source: https://context7.com/wilson-1024/mgson/llms.txt MGson ensures safe parsing for all numeric types (int, long, double, float, and their wrappers). When a numeric field receives non-numeric data (like objects, arrays, booleans, or unparseable strings), it defaults to 0. It also supports converting string representations of numbers. ```java import com.chemanman.lib_mgson.MGson; import com.google.gson.Gson; public class Order { public int orderId; public long totalPrice; public double discount; public float weight; } Gson gson = MGson.newGson(); // Scenario 1: Numeric field returns object {} - defaults to 0 String json1 = "{\"orderId\":{},\"totalPrice\":100,\"discount\":0.8,\"weight\":2.5}"; Order order1 = gson.fromJson(json1, Order.class); // Output: Order{orderId=0, totalPrice=100, discount=0.8, weight=2.5} // Scenario 2: Numeric field returns array [] - defaults to 0 String json2 = "{\"orderId\":[],\"totalPrice\":100,\"discount\":0.8,\"weight\":2.5}"; Order order2 = gson.fromJson(json2, Order.class); // Output: Order{orderId=0, totalPrice=100, discount=0.8, weight=2.5} // Scenario 3: Numeric field returns string number "123" - auto-converts String json3 = "{\"orderId\":\"456\",\"totalPrice\":\"100\",\"discount\":\"0.8\",\"weight\":\"2.5\"}"; Order order3 = gson.fromJson(json3, Order.class); // Output: Order{orderId=456, totalPrice=100, discount=0.8, weight=2.5} // Scenario 4: Numeric field returns null - defaults to 0 String json4 = "{\"orderId\":null,\"totalPrice\":null,\"discount\":null,\"weight\":null}"; Order order4 = gson.fromJson(json4, Order.class); // Output: Order{orderId=0, totalPrice=0, discount=0.0, weight=0.0} // Scenario 5: Numeric field returns boolean - defaults to 0 String json5 = "{\"orderId\":true,\"totalPrice\":false,\"discount\":0.8,\"weight\":2.5}"; Order order5 = gson.fromJson(json5, Order.class); // Output: Order{orderId=0, totalPrice=0, discount=0.8, weight=2.5} ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.