### Client-side JSONP Request Example (curl) Source: https://github.com/alibaba/fastjson/wiki/FastJsonpHttpMessageConverter4_CN-(已废弃) This example demonstrates how a client can make a JSONP request to a backend service using curl. It shows how to specify the callback function name and the parameter name used by the server. ```bash curl http://server:port/user/find/1?callback=javaScriptFunction ``` -------------------------------- ### Fastjson Serialization and Deserialization Example (Java) Source: https://github.com/alibaba/fastjson/wiki/Quick-Start-CN Demonstrates the basic usage of Fastjson for serializing a Java object to a JSON string and deserializing a JSON string back into a Java object. This is a fundamental operation for using the library. ```java String text = JSON.toJSONString(obj); // Serialization VO vo = JSON.parseObject("{...}", VO.class); // Deserialization ``` -------------------------------- ### Example Usage of Type Registration APIs Source: https://github.com/alibaba/fastjson/wiki/android_first_codec_optimize This example demonstrates how to use the `registerIfNotExists` methods from `ParserConfig` and `SerializeConfig` to pre-register type information for a `MediaContent` class. This approach bypasses potentially expensive reflection calls like `Class.getModifiers`, `getAnnotation`, `getGenericType`, and `getMethods` during the initial serialization or deserialization process, leading to performance gains. ```java ParserConfig.getGlobalInstance() .registerIfNotExists(MediaContent.class, Modifier.PUBLIC, true, false, false, false); SerializeConfig.getGlobalInstance() .registerIfNotExists(MediaContent.class, Modifier.PUBLIC, true, false, false, false); ``` -------------------------------- ### Configure Fastjson AutoType Whitelist via properties file Source: https://github.com/alibaba/fastjson/wiki/enable_autotype In specific Fastjson versions (1.2.25/1.2.26), the AutoType whitelist can be configured using a `fastjson.properties` file located in the classpath. Package prefixes are separated by commas. ```properties fastjson.parser.autoTypeAccept=com.taobao.pac.client.sdk.dataobject.,com.cainiao. ``` -------------------------------- ### JSON Data Example for Media Serialization Source: https://github.com/alibaba/fastjson/wiki/Benchmark_1_2_11 This is a sample JSON payload representing MediaContent. It includes nested objects and arrays, showcasing the structure that the serialization libraries process. This data is used in the performance tests. ```json {"images":[{"height":768,"size":"LARGE","title":"Javaone Keynote","uri":"http://javaone.com/keynote_large.jpg","width":1024},{"height":240,"size":"SMALL","title":"Javaone Keynote","uri":"http://javaone.com/keynote_small.jpg","width":320}],"media":{"bitrate":262144,"duration":18000000,"format":"video/mpg4","height":480,"persons":["Bill Gates","Steve Jobs"],"player":"JAVA","size":58982400,"title":"Javaone Keynote","uri":"http://javaone.com/keynote.mpg","width":640}} ``` -------------------------------- ### User Java Class Definition Source: https://github.com/alibaba/fastjson/wiki/Samples-DataBind This is the Java class definition for a 'User' object, used in Fastjson examples. It includes fields for ID and name, along with standard getter and setter methods. ```java public class User { private Long id; private String name; public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } } ``` -------------------------------- ### Configure Fastjson SafeMode via fastjson.properties File Source: https://github.com/alibaba/fastjson/wiki/fastjson_safemode This example illustrates configuring Fastjson's SafeMode by creating or modifying a `fastjson.properties` file within the classpath. This approach allows for configuration without altering application code or JVM arguments. ```properties fastjson.parser.safeMode=true ``` -------------------------------- ### JSONPath Evaluation Example (Java) Source: https://github.com/alibaba/fastjson/wiki/JSONPath Demonstrates the usage of `JSONPath.eval`, `JSONPath.contains`, `JSONPath.containsValue`, and `JSONPath.size` methods with a custom `Entity` class. This example verifies basic querying and checking functionalities of JSONPath. ```java public void test_entity() throws Exception { Entity entity = new Entity(123, new Object()); Assert.assertSame(entity.getValue(), JSONPath.eval(entity, "$.value")); Assert.assertTrue(JSONPath.contains(entity, "$.value")); Assert.assertTrue(JSONPath.containsValue(entity, "$.id", 123)); Assert.assertTrue(JSONPath.containsValue(entity, "$.value", entity.getValue())); Assert.assertEquals(2, JSONPath.size(entity, "$")); Assert.assertEquals(0, JSONPath.size(new Object[], "$")); } public static class Entity { private Integer id; private String name; private Object value; public Entity() {} public Entity(Integer id, Object value) { this.id = id; this.value = value; } public Entity(Integer id, String name) { this.id = id; this.name = name; } public Entity(String name) { this.name = name; } public Integer getId() { return id; } public Object getValue() { return value; } public String getName() { return name; } public void setId(Integer id) { this.id = id; } public void setName(String name) { this.name = name; } public void setValue(Object value) { this.value = value; } } ``` -------------------------------- ### Example JSON Object Structure Source: https://github.com/alibaba/fastjson/blob/master/rfc4627.txt This is a sample JSON object illustrating nested structures, including objects within objects and arrays. It represents data for an image, with properties like width, height, title, thumbnail details, and a list of IDs. This example is useful for understanding the hierarchical nature of JSON data representation. ```json { "Image": { "Width": 800, "Height": 600, "Title": "View from 15th Floor", "Thumbnail": { "Url": "http://www.example.com/image/481989943", "Height": 125, "Width": "100" }, "IDs": [116, 943, 234, 38793] } } ``` -------------------------------- ### MixInAnnotations Usage Example - Java Source: https://github.com/alibaba/fastjson/wiki/MixInAnnotations_cn Demonstrates how to use MixInAnnotations to customize the serialization and deserialization of a third-party `Rectangle` class. It shows renaming properties ('w' to 'width', 'h' to 'height') and excluding a method ('getSize') from serialization. The example includes adding, serializing, deserializing, and removing MixIn configurations. ```Java public final class Rectangle { final private int w, h; public Rectangle(int w, int h) { this.w = w; this.h = h; } public int getW() { return w; } public int getH() { return h; } public int getSize() { return w * h; } } abstract class MixIn { @JSONField(name="width") abstract int getW(); // 重命名属性 @JSONField(name="height") abstract int getH(); // 重命名属性 @JSONField(serialize=false) abstract int getSize(); // 不序列化的属性 } //关联Target类与MixIn类 JSON.addMixInAnnotations(Rectangle.class, MixIn.class); // 序列化 Rectangle rectangle = new Rectangle(5, 10); String str = JSON.toJSONString(rectangle); System.out.println(str); // {"width":5, "height":10} //反序列化 Rectangle rectangle2 = JSON.parseObject(str, Rectangle.class); System.out.println(rectangle2.getW()); // 5 System.out.println(rectangle2.getH()); // 10 //移除关联 JSON.removeMixInAnnotations(Rectangle.class); ``` -------------------------------- ### Configure Fastjson AutoType Whitelist via JVM Argument Source: https://github.com/alibaba/fastjson/wiki/enable_autotype This approach configures the AutoType whitelist by setting a JVM system property. It allows specifying multiple package prefixes separated by commas. This is a convenient way to manage the whitelist without modifying application code. ```script -Dfastjson.parser.autoTypeAccept=com.taobao.pac.client.sdk.dataobject.,com.cainiao. ``` -------------------------------- ### Group Java Class Definition Source: https://github.com/alibaba/fastjson/wiki/Samples-DataBind This is the Java class definition for a 'Group' object, used in Fastjson examples. It includes fields for ID, name, and a list of 'User' objects, along with standard getter, setter, and helper methods. ```java import java.util.ArrayList; import java.util.List; public class Group { private Long id; private String name; private List users = new ArrayList(); public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public List getUsers() { return users; } public void setUsers(List users) { this.users = users; } public void addUser(User user) { users.add(user); } } ``` -------------------------------- ### Example JSON Array of Objects Source: https://github.com/alibaba/fastjson/blob/master/rfc4627.txt This JSON snippet shows an array containing two distinct JSON objects. Each object represents a location with detailed address information, including precision, latitude, longitude, city, state, zip code, and country. This example is helpful for understanding how to represent lists of structured data in JSON. ```json [ { "precision": "zip", "Latitude": 37.7668, "Longitude": -122.3959, "Address": "", "City": "SAN FRANCISCO", "State": "CA", "Zip": "94107", "Country": "US" }, { "precision": "zip", "Latitude": 37.371991, "Longitude": -122.026020, "Address": "", "City": "SUNNYVALE", "State": "CA", "Zip": "94085", "Country": "US" } ] ``` -------------------------------- ### Configuring JSONField on Fields Source: https://github.com/alibaba/fastjson/wiki/JSONField Illustrates applying the @JSONField annotation directly to a field to specify its JSON name. This example renames the 'id' field to 'ID' for serialization and deserialization. ```java public class A { @JSONField(name="ID") private int id; public int getId() {return id;} public void setId(int value) {this.id = id;} } ``` -------------------------------- ### Enable Fastjson AutoType via JVM Argument Source: https://github.com/alibaba/fastjson/wiki/enable_autotype This method enables the AutoType functionality in Fastjson by setting a JVM system property. While convenient, enabling AutoType might introduce security risks if not properly managed with whitelisting or blacklisting. ```script -Dfastjson.parser.autoTypeSupport=true ``` -------------------------------- ### Configuring JSONField on Getter/Setter Methods Source: https://github.com/alibaba/fastjson/wiki/JSONField Demonstrates how to apply the @JSONField annotation to getter and setter methods to control field naming during JSON processing. This example shows renaming the 'id' field to 'ID'. ```java public class A { private int id; @JSONField(name="ID") public int getId() {return id;} @JSONField(name="ID") public void setId(int value) {this.id = id;} } ``` -------------------------------- ### Fastjson Custom Deserialization Example (Java) Source: https://github.com/alibaba/fastjson/wiki/PropertyProcessable_cn An example implementation of the PropertyProcessable interface within a VO class. This demonstrates how to override getType and apply methods to handle custom property types and apply values during JSON deserialization using Fastjson. ```java public static class VO implements PropertyProcessable { public int id; public String name; public Value value; public Type getType(String name) { if ("value".equals(name)) { return Value.class; } return null; } public void apply(String name, Object value) { if ("vo_id".equals(name)) { this.id = ((Integer) value).intValue(); } else if ("vo_name".equals(name)) { this.name = (String) value; } else if ("value".equals(name)) { this.value = (Value) value; } } } public static class Value { } ///////////// 使用 VO vo = JSON.parseObject("{\"vo_id\":123,\"vo_name\":\"abc\",\"value\":{}}", VO.class); assertEquals(123, vo.id); assertEquals("abc", vo.name); assertNotNull(vo.value); ``` -------------------------------- ### Fastjson SerializerFeature Examples Source: https://context7.com/alibaba/fastjson/llms.txt Illustrates how to control JSON output formatting and behavior during serialization using SerializerFeature. Supports pretty printing, including null values, writing class type information, disabling circular reference detection, sorting fields, and date formatting. ```java import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.serializer.SerializerFeature; import java.util.Date; import java.util.List; class Product { private String name; private Double price; private String description; // might be null private List tags; // might be null // constructor, getters, setters } Product product = new Product("Laptop", 999.99, null, null); // Pretty print with indentation String pretty = JSON.toJSONString(product, SerializerFeature.PrettyFormat); // Include null values String withNulls = JSON.toJSONString(product, SerializerFeature.WriteMapNullValue, SerializerFeature.WriteNullStringAsEmpty, SerializerFeature.WriteNullListAsEmpty); // Output includes: "description":"", "tags":[] // Write class type information for polymorphism String withType = JSON.toJSONString(product, SerializerFeature.WriteClassName); // Disable circular reference detection for better performance String optimized = JSON.toJSONString(product, SerializerFeature.DisableCircularReferenceDetect); // Sort fields alphabetically String sorted = JSON.toJSONString(product, SerializerFeature.SortField); // Date formatting Date now = new Date(); String dateJson = JSON.toJSONString(now, SerializerFeature.WriteDateUseDateFormat); // Multiple features combined String formatted = JSON.toJSONString(product, SerializerFeature.PrettyFormat, SerializerFeature.WriteMapNullValue, SerializerFeature.SortField, SerializerFeature.DisableCircularReferenceDetect); ``` -------------------------------- ### Configure Fastjson AutoType Deny List via JVM Argument Source: https://github.com/alibaba/fastjson/wiki/enable_autotype This approach configures Fastjson's AutoType deny list using a JVM system property. It allows specifying package prefixes to be blocked from deserialization. Multiple entries can be separated by commas. ```script -Dfastjson.parser.deny=xx.xxx ``` -------------------------------- ### JSONPath Query Language Examples Source: https://context7.com/alibaba/fastjson/llms.txt Demonstrates how to use JSONPath for querying and extracting data from JSON structures. Supports basic path evaluation, array access, filtering, deep scans, size/contains operations, and value modification. It can also extract data directly from a JSON string for efficiency. ```java import com.alibaba.fastjson.JSONPath; // Sample data structure String json = "{\"store\":{\"book\":[ {\"category\":\"reference\",\"author\":\"Nigel Rees\",\"title\":\"Sayings\",\"price\":8.95}, {\"category\":\"fiction\",\"author\":\"Evelyn Waugh\",\"title\":\"Sword of Honour\",\"price\":12.99}, {\"category\":\"fiction\",\"author\":\"J.R.R. Tolkien\",\"title\":\"The Lord of the Rings\",\"price\":22.99} ],"bicycle":{\"color\":\"red\",\"price\":19.95}}"; Object document = JSON.parse(json); // Basic path evaluation Object title = JSONPath.eval(document, "$.store.book[0].title"); // Result: "Sayings" // Array access Object allBooks = JSONPath.eval(document, "$.store.book[*]"); Object lastBook = JSONPath.eval(document, "$.store.book[-1].title"); // Result: "The Lord of the Rings" // Filtering Object expensiveBooks = JSONPath.eval(document, "$.store.book[price > 10]"); Object fictionBooks = JSONPath.eval(document, "$.store.book[category = 'fiction']"); // Deep scan Object allPrices = JSONPath.eval(document, "$..price"); // Size and contains operations int bookCount = JSONPath.size(document, "$.store.book"); boolean hasBook = JSONPath.contains(document, "$.store.book[0]"); boolean hasPrice = JSONPath.containsValue(document, "$.store.bicycle.price", 19.95); // Modify values JSONPath.set(document, "$.store.book[0].price", 9.95); // Extract from JSON string directly (more efficient) Object result = JSONPath.extract(json, "$.store.book[0].title"); ``` -------------------------------- ### Enable Fastjson AutoType in Code Source: https://github.com/alibaba/fastjson/wiki/enable_autotype This code snippet demonstrates how to programmatically enable the AutoType feature within an application. If a non-global `ParserConfig` instance is used, `setAutoTypeSupport(true)` must be called on that specific instance. ```java ParserConfig.getGlobalInstance().setAutoTypeSupport(true); ``` -------------------------------- ### Fastjson JSONField Annotation for Raw Values Source: https://github.com/alibaba/fastjson/wiki/guid_to_migrating_from_jackson_to_fastjson_cn Illustrates how to use the @JSONField annotation with the jsonDirect=true configuration in Fastjson to handle raw JSON values, akin to Jackson's JsonRawValue. ```java public static class Model { public int id; @JSONField(jsonDirect=true) public String value; } ``` -------------------------------- ### Static Inner Class Example (Java) Source: https://github.com/alibaba/fastjson/wiki/non_static_inner_class_support_cn Demonstrates the definition of a static inner class within a Java class. Static inner classes do not require an instance of the outer class to be created. ```java public class Model { public static class Item { } } ``` -------------------------------- ### Fastjson Serializable Entity Class 'A' Source: https://github.com/alibaba/fastjson/wiki/Samples-PropertyFilter This is a simple Java POJO class named 'A' with two private fields: 'id' (int) and 'name' (String). It includes standard getter and setter methods for both fields, making it suitable for serialization and deserialization with libraries like Fastjson. ```java public static class A { private int id; private String name; public int getId() { return id; } public void setId(int id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } } ``` -------------------------------- ### Configure Fastjson AutoType Whitelist in Code Source: https://github.com/alibaba/fastjson/wiki/enable_autotype This method allows developers to programmatically add specific package prefixes to Fastjson's AutoType whitelist. This is useful for allowing deserialization of specific types that would otherwise be restricted. Multiple package prefixes can be added by calling addAccept multiple times. ```java ParserConfig.getGlobalInstance().addAccept("com.taobao.pac.client.sdk.dataobject."); ``` -------------------------------- ### Configure FastJsonJsonView for Spring MVC Source: https://github.com/alibaba/fastjson/wiki/FastJsonJsonView_EN Sets up FastJsonJsonView as a Spring MVC view. This view is responsible for serializing model data into JSON format using Fastjson. It requires a reference to a configured FastJsonConfig bean to define its behavior. This is part of a ContentNegotiatingViewResolver setup. ```xml ``` -------------------------------- ### Fastjson Parser Feature Examples Source: https://context7.com/alibaba/fastjson/llms.txt Shows how to control parsing behavior and JSON compliance during deserialization using Feature. Supports parsing non-standard JSON with unquoted field names and single quotes, handling comments, using BigDecimal for precision, ignoring unknown fields, initializing string fields as empty, and supporting array to bean conversion. ```java import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.JSONObject; import com.alibaba.fastjson.parser.Feature; import java.math.BigDecimal; // Assuming User class exists with appropriate fields and methods // class User { public String name; public int age; public String city; /* ... */ } // Parse JSON with non-standard format String relaxedJson = "{name: 'John', age: 30, 'city': \"NYC\"}"; JSONObject obj = JSON.parseObject(relaxedJson, Feature.AllowUnQuotedFieldNames, Feature.AllowSingleQuotes); // Parse with comments (non-standard JSON) String jsonWithComments = "{\n" + " // This is a comment\n" + " \"name\": \"Alice\"\n" + "}"; JSONObject withComments = JSON.parseObject(jsonWithComments, Feature.AllowComment); // Use BigDecimal for all decimal numbers (avoid precision loss) String numJson = "{\"price\": 99.99, \"tax\": 8.875}"; JSONObject precise = JSON.parseObject(numJson, Feature.UseBigDecimal); BigDecimal price = precise.getBigDecimal("price"); // Ignore unknown fields during deserialization String extraFields = "{\"name\":\"Bob\",\"age\":25,\"unknownField\":\"value\"}"; // User user = JSON.parseObject(extraFields, User.class, Feature.IgnoreNotMatch); // Initialize string fields as empty string instead of null // User emptyStrings = JSON.parseObject("{\"name\":\"Alice\"}", User.class, // Feature.InitStringFieldAsEmpty); // Support array to bean conversion String arrayFormat = "[\"Alice\", 25, \"alice@example.com\"]"; // User fromArray = JSON.parseObject(arrayFormat, User.class, // Feature.SupportArrayToBean); // Disable circular reference detection String json = "{\"name\":\"test\"}"; Object obj = JSON.parseObject(json, Feature.DisableCircularReferenceDetect); ``` -------------------------------- ### Configure Fastjson AutoType Deny List in Code Source: https://github.com/alibaba/fastjson/wiki/enable_autotype This method allows developers to programmatically add package prefixes to Fastjson's AutoType deny list. This is used to prevent deserialization of potentially risky types. Multiple entries can be added by calling addDeny multiple times. ```java ParserConfig.getGlobalInstance().addDeny("xx.xxx"); ``` -------------------------------- ### MixInAnnotations Configuration Switching - Java Source: https://github.com/alibaba/fastjson/wiki/MixInAnnotations_cn Illustrates the ability to switch between different MixIn configurations for the same target class. The example shows applying a default MixIn, then switching to a Chinese locale-specific MixIn (MixIn_CN) that renames properties to Chinese terms, and finally removing the MixIn configuration to revert to default behavior. ```Java abstract class MixIn_CN { @JSONField(name="长度") abstract int getW(); // 重命名属性 @JSONField(name="宽度") abstract int getH(); // 重命名属性 @JSONField(serialize=false) abstract int getSize(); // 不序列化的属性 } //关联Target类与MixIn类 JSON.addMixInAnnotations(Rectangle.class, MixIn.class); // 序列化 Rectangle rectangle = new Rectangle(5, 10); String str = JSON.toJSONString(rectangle); System.out.println(str); // {"width":5, "height":10} //关联Target类与MixIn_CN类 JSON.addMixInAnnotations(Rectangle.class, MixIn_CN.class); // 序列化 str = JSON.toJSONString(rectangle); System.out.println(str); // {"宽度":5, "长度":10} //移除Target类的关联关系 JSON.removeMixInAnnotations(Rectangle.class); // 序列化 str = JSON.toJSONString(rectangle); System.out.println(str); // {"h":10,"size":50,"w":5} ``` -------------------------------- ### Parsing and Serializing GeoJSON with Fastjson (Java) Source: https://github.com/alibaba/fastjson/wiki/geojson_cn This example demonstrates how to parse a GeoJSON string into a Fastjson Geometry object and then serialize the Geometry object back into a GeoJSON string. It showcases the use of `JSON.parseObject` and `JSON.toJSONString` for GeoJSON data manipulation. No external dependencies are required beyond Fastjson. ```java String str = "{\"type\": \"MultiPoint\",\n" + " \"coordinates\": [\n" + " [100.0, 0.0],\n" + " [101.0, 1.0]\n" + " ]\n" + "}"; Geometry geometry = JSON.parseObject(str, Geometry.class); assertEquals(MultiPoint.class, geometry.getClass()); assertEquals("{\"type\":\"MultiPoint\",\"coordinates\":[[100.0,0.0],[101.0,1.0]]}", JSON.toJSONString(geometry)); String str2 = JSON.toJSONString(geometry); assertEquals(str2, JSON.toJSONString(JSON.parseObject(str2, Geometry.class))); ``` -------------------------------- ### Fastjson: Extract Object Property Names using keySet Source: https://github.com/alibaba/fastjson/wiki/JSONPath This example demonstrates how to extract the property names of an object using Fastjson's `keySet()` method via JSONPath. It highlights that null properties are excluded by default and shows alternative ways to invoke `keySet()`. ```java Entity e = new Entity(); e.setId(null); e.setName("hello"); Map map = Collections.singletonMap("e", e); Collection result; // id is null, excluded by keySet result = (Collection)JSONPath.eval(map, "$.e.keySet()"); assertEquals(1, result.size()); Assert.assertTrue(result.contains("name")); e.setId(1L); result = (Collection)JSONPath.eval(map, "$.e.keySet()"); Assert.assertEquals(2, result.size()); Assert.assertTrue(result.contains("id")); // included Assert.assertTrue(result.contains("name")); // Same result Assert.assertEquals(result, JSONPath.keySet(map, "$.e")); Assert.assertEquals(result, new JSONPath("$.e").keySet(map)); ``` -------------------------------- ### Decode JSON String to Java Object with Fastjson Source: https://github.com/alibaba/fastjson/wiki/Samples-DataBind This snippet demonstrates how to parse a JSON string into a specific Java object type using Fastjson's `JSON.parseObject()` method. It requires the Fastjson library and the target Java class (e.g., Group.class) to be defined and accessible. ```java import com.alibaba.fastjson.JSON; // Assume Group class is defined elsewhere String jsonString = "{\"id\":0,\"name\":\"admin\",\"users\":[{\"id\":2,\"name\":\"guest\"},{\"id\":3,\"name\":\"root\"}]}"; // Example JSON string Group group = JSON.parseObject(jsonString, Group.class); ``` -------------------------------- ### Fastjson Java JSON Encoding Example Source: https://github.com/alibaba/fastjson/blob/master/src/test/resources/1.txt Demonstrates how to serialize a Java object (Group containing User objects) into a JSON string using Fastjson's `toJSONString` method. This is useful for sending data over a network or storing it in a JSON format. ```java import com.alibaba.fastjson.JSON; import java.util.ArrayList; import java.util.List; public class User { private Long id; private String name; public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } } public class Group { private Long id; private String name; private List users = new ArrayList(); public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public List getUsers() { return users; } public void setUsers(List users) { this.users = users; } } public class FastjsonEncodeExample { public static void main(String[] args) { Group group = new Group(); group.setId(0L); group.setName("admin"); User guestUser = new User(); guestUser.setId(2L); guestUser.setName("guest"); User rootUser = new User(); rootUser.setId(3L); rootUser.setName("root"); group.getUsers().add(guestUser); group.getUsers().add(rootUser); String jsonString = JSON.toJSONString(group); System.out.println(jsonString); } } ``` -------------------------------- ### Fastjson Custom Enum and Model Definition (Java) Source: https://github.com/alibaba/fastjson/wiki/ObjectDeserializer_cn Defines a sample `OrderActionEnum` enum and a `Msg` class that uses this enum. This serves as the model for the custom deserialization example, demonstrating a scenario where a custom deserializer is needed for the `actionEnum` field. ```java import com.alibaba.fastjson.annotation.JSONField; public static enum OrderActionEnum { FAIL(1), SUCC(0); private int code; OrderActionEnum(int code){ this.code = code; } public int getCode() { return code; } } public static class Msg { public OrderActionEnum actionEnum; public String body; } ``` -------------------------------- ### Java: Parse JSON String to Java Object with Fastjson Source: https://github.com/alibaba/fastjson/wiki/ReuseObject_cn This snippet shows how to parse a JSON string into a Java object using Fastjson's DefaultJSONParser. It includes defining a simple data model, creating a parser instance, parsing the JSON into the model, and asserting the parsed values. Calling parser.close() is recommended for buffer reuse and performance. ```java public static class Model { public int id; public String name; } Model model = new Model(); { DefaultJSONParser parser = new DefaultJSONParser("{\"id\":123,\"name\":\"wangsai-silence\"}"); parser.parseObject(model); parser.close(); // 调用close能重用buf,提升性能 // assertEquals(123, model.id); // assertEquals("wangsai-silence", model.name); } { DefaultJSONParser parser = new DefaultJSONParser("{\"id\":234,\"name\":\"wenshao\"}"); parser.parseObject(model); parser.close(); // 调用close能重用buf,提升性能 // assertEquals(234, model.id); // assertEquals("wenshao", model.name); } ``` -------------------------------- ### Encode Java Object to JSON String with Fastjson Source: https://github.com/alibaba/fastjson/wiki/Samples-DataBind This snippet shows how to convert a Java object, including nested objects and collections, into a JSON string using Fastjson's `JSON.toJSONString()` method. It requires the Fastjson library and the relevant Java classes (Group, User) to be defined. ```java import com.alibaba.fastjson.JSON; // Assume Group and User classes are defined elsewhere Group group = new Group(); group.setId(0L); group.setName("admin"); User guestUser = new User(); guestUser.setId(2L); guestUser.setName("guest"); User rootUser = new User(); rootUser.setId(3L); rootUser.setName("root"); group.addUser(guestUser); group.addUser(rootUser); String jsonString = JSON.toJSONString(group); System.out.println(jsonString); ``` -------------------------------- ### Running Serialization Benchmarks with Make Source: https://github.com/alibaba/fastjson/wiki/Benchmark_1_2_11 This command executes a benchmark suite for various serialization libraries. It clones a repository, navigates to the test directory, and runs a shell script to perform the tests. The script takes a comma-separated list of serialization formats to test. ```bash git clone https://github.com/wenshao/jvm-serializers.git cd jvm-serializers/tpc make ./run-bench.sh json/jackson+afterburner/databind,json/fastjson/databind,json/fastjson_array/databind,protobuf,json/jackson/databind,msgpack/databind ``` -------------------------------- ### Configure Fastjson SafeMode via JVM Argument (Script) Source: https://github.com/alibaba/fastjson/wiki/fastjson_safemode This shows how to activate Fastjson's SafeMode by setting a JVM startup parameter. This method is useful for global configuration across applications running on the same JVM. ```bash -Dfastjson.parser.safeMode=true ``` -------------------------------- ### Disabling Deserialization with JSONField Source: https://github.com/alibaba/fastjson/wiki/JSONField Illustrates how to prevent a field from being deserialized from JSON by setting 'deserialize' to false in the @JSONField annotation. This example ensures the 'date' field is not populated from incoming JSON. ```java public class A { @JSONField(deserialize=false) public Date date; } ``` -------------------------------- ### Disabling Serialization with JSONField Source: https://github.com/alibaba/fastjson/wiki/JSONField Demonstrates how to prevent a field from being serialized into JSON by setting 'serialize' to false within the @JSONField annotation. This example excludes the 'date' field from JSON output. ```java public class A { @JSONField(serialize=false) public Date date; } ``` -------------------------------- ### Configure FastJSON JSONP HTTP Message Converter (Java - Spring Boot) Source: https://github.com/alibaba/fastjson/wiki/FastJsonpHttpMessageConverter4_CN-(已废弃) This Java configuration is tailored for Spring Boot projects to enable FastJSON's JSONP support. It simplifies the setup by defining the necessary beans without requiring inheritance from WebMvcConfigurerAdapter. ```java @Configuration public class Config{ @Bean public FastJsonpResponseBodyAdvice fastJsonpResponseBodyAdvice() { return new FastJsonpResponseBodyAdvice("callback", "jsonp"); } @Bean public FastJsonpHttpMessageConverter4 fastJsonpHttpMessageConverter4() { return new FastJsonpHttpMessageConverter4(); } } ``` -------------------------------- ### Fastjson Main API: JSON Serialization and Deserialization Source: https://github.com/alibaba/fastjson/wiki/FAQ(English-Version) Demonstrates the core usage of the Fastjson library for converting Java objects to JSON strings (serialization) and parsing JSON strings back into Java objects (deserialization). It also shows how to deserialize a JSON string into a List of objects. ```java package com.alibaba.fastjson; public abstract class JSON { public static final String toJSONString(Object object); public static final T parseObject(String text, Class clazz, Feature... features); } ``` ```java String jsonString = JSON.toJSONString(obj); ``` ```java VO vo = JSON.parseObject("...", VO.class); ``` ```java import com.alibaba.fastjson.TypeReference; List list = JSON.parseObject("...", new TypeReference>() {}); ``` -------------------------------- ### XML: Full Spring Data Redis Configuration with Fastjson Source: https://github.com/alibaba/fastjson/wiki/在-Spring-中集成-Fastjson This comprehensive XML configuration includes settings for the Redis connection pool, connection factory, and RedisTemplate. It specifically sets GenericFastJsonRedisSerializer as the default, key, and value serializer for the RedisTemplate. This provides a complete setup for using Fastjson with Spring Data Redis in an XML-based Spring context. ```xml ``` -------------------------------- ### Maven Dependency Configuration for Fastjson Source: https://github.com/alibaba/fastjson/wiki/常见问题 This snippet shows how to add Fastjson as a dependency in a Maven project. It includes configurations for both the standard and Android versions of the library. ```xml com.alibaba fastjson 1.2.70 ``` ```xml com.alibaba fastjson 1.1.68.android ``` -------------------------------- ### Add Fastjson Maven Dependency Source: https://github.com/alibaba/fastjson/wiki/FAQ(English-Version) This snippet shows how to add the Fastjson library as a Maven dependency to your project. It includes separate configurations for standard Java projects and Android projects. ```xml com.alibaba fastjson 1.2.12 ``` ```xml com.alibaba fastjson 1.1.52.android ``` -------------------------------- ### Fastjson Maven Dependency Configuration (XML) Source: https://github.com/alibaba/fastjson/wiki/Quick-Start-CN Shows how to add Fastjson as a dependency to a Maven project. This is the recommended way to include the library in modern Java projects, allowing Maven to manage the version and transitive dependencies. ```xml com.alibaba fastjson x.x.x ``` -------------------------------- ### Gradle Dependency for Fastjson Source: https://github.com/alibaba/fastjson/wiki/Home This snippet demonstrates how to add the Fastjson library as a dependency in your Gradle project. Remember to replace VERSION_CODE with the actual version. ```groovy compile 'com.alibaba:fastjson:VERSION_CODE' ``` -------------------------------- ### Rectangle Class Definition Source: https://github.com/alibaba/fastjson/wiki/MixInAnnotations_en A sample `Rectangle` class, likely from a third-party library, used in the MixInAnnotations example. It has private fields `w` and `h` with public getter methods. ```Java public final class Rectangle { final private int w, h; public Rectangle(int w, int h) { this.w = w; this.h = h; } public int getW() { return w; } public int getH() { return h; } public int getSize() { return w * h; } } ``` -------------------------------- ### Configure FastJSONProvider for JAX-RS Services Source: https://github.com/alibaba/fastjson/wiki/FastJsonProvider_CN This XML configuration sets up the FastJsonProvider bean, which integrates FastJSON's serialization and deserialization capabilities into JAX-RS services. It references the FastJsonConfig bean for specific settings and is then included in the JAX-RS server definition. ```xml ``` -------------------------------- ### Fastjson JSONType Annotation for Field Order Source: https://github.com/alibaba/fastjson/wiki/guid_to_migrating_from_jackson_to_fastjson_cn Demonstrates how to use the @JSONType annotation in Fastjson to specify the order of fields during serialization, similar to Jackson's JsonPropertyOrder. ```java @JSONType(orders={"name", "id"}) public static class VO { public int id; public String name; } ``` -------------------------------- ### Benchmark Fastjson read10FromString POJO list Source: https://github.com/alibaba/fastjson/wiki/Benchmark_1_2_11_x Compares the performance of reading a list of 10 POJOs from a string across various JSON libraries. The benchmark is executed using a Java JAR file and reports results in operations per second (ops/s). ```shell java -Xmx256m -jar target/microbenchmarks.jar ".*DZoneReadPojo.*read10FromString.*" -wi 4 -i 5 -f 9 ``` -------------------------------- ### JSONField Annotation Definition Source: https://github.com/alibaba/fastjson/wiki/JSONField Defines the @JSONField annotation used in Fastjson for customizing JSON processing. It includes attributes for ordinal, name, format, serialize, and deserialize. ```java package com.alibaba.fastjson.annotation; public @interface JSONField { // 配置序列化和反序列化的顺序,1.1.42版本之后才支持 int ordinal() default 0; // 指定字段的名称 String name() default ""; // 指定字段的格式,对日期格式有用 String format() default ""; // 是否序列化 boolean serialize() default true; // 是否反序列化 boolean deserialize() default true; } ``` -------------------------------- ### Fastjson JSONPath API Reference (Java) Source: https://github.com/alibaba/fastjson/wiki/JSONPath This snippet outlines the core static methods provided by the `com.alibaba.fastjson.JSONPath` class for querying and manipulating JSON data. It includes methods for evaluation, size calculation, containment checks, setting values, adding to arrays/collections, and retrieving keysets. ```java package com.alibaba.fastjson; public class JSONPath { // 求值,静态方法 public static Object eval(Object rootObject, String path); // 求值,静态方法,按需计算,性能更好 public static Object extract(String json, String path); // 计算Size,Map非空元素个数,对象非空元素个数,Collection的Size,数组的长度。其他无法求值返回-1 public static int size(Object rootObject, String path); // 是否包含,path中是否存在对象 public static boolean contains(Object rootObject, String path) { } // 是否包含,path中是否存在指定值,如果是集合或者数组,在集合中查找value是否存在 public static boolean containsValue(Object rootObject, String path, Object value) { } // 修改制定路径的值,如果修改成功,返回true,否则返回false public static boolean set(Object rootObject, String path, Object value) {} // 在数组或者集合中添加元素 public static boolean arrayAdd(Object rootObject, String path, Object... values); // 获取,Map的KeySet,对象非空属性的名称。数组、Collection等不支持类型返回null。 public static Set keySet(Object rootObject, String path); } ``` -------------------------------- ### Using JSONField format for Date Formatting Source: https://github.com/alibaba/fastjson/wiki/JSONField Shows how to use the 'format' attribute within the @JSONField annotation to specify a custom date format ('yyyyMMdd') for both serialization and deserialization of a Date field. ```java public class A { // 配置date序列化和反序列使用yyyyMMdd日期格式 @JSONField(format="yyyyMMdd") public Date date; } ``` -------------------------------- ### Benchmark Fastjson write1kUsingStream Source: https://github.com/alibaba/fastjson/wiki/Benchmark_1_2_11_x Assesses the performance of writing 1000 items using streams across different JSON libraries. The benchmark is run via a Java JAR file, with results in operations per second (ops/s). Note: An error was reported for accessing the JAR file. ```shell java -Xmx256m -jar target/microbenchmarks.jar ".*DZoneWrite.*write1k.*UsingStream.*" -wi 4 -i 5 -f 19 ``` -------------------------------- ### Non-Static Inner Class Example (Java) Source: https://github.com/alibaba/fastjson/wiki/non_static_inner_class_support_cn Illustrates the definition of a non-static inner class in Java. Non-static inner classes implicitly hold a reference to an instance of the outer class, which complicates deserialization. ```java public class Model { public class Item { } } // Constructor for non-static inner class Item (Model modelThis) {} ``` -------------------------------- ### Maven Dependency for Fastjson Source: https://github.com/alibaba/fastjson/wiki/Home This snippet shows how to include the Fastjson library in your Maven project. Replace VERSION_CODE with the desired version number. ```xml com.alibaba fastjson VERSION_CODE ``` -------------------------------- ### Fastjson: Retrieve Subset of Collection by Index Range Source: https://github.com/alibaba/fastjson/wiki/JSONPath This example shows how to extract a subset of a Java List based on an index range using Fastjson's JSONPath. It utilizes the `JSONPath.eval()` method with a range expression. ```java List entities = new ArrayList(); entities.add(new Entity("wenshao")); entities.add(new Entity("ljw2083")); entities.add(new Entity("Yako")); List result = (List)JSONPath.eval(entities, "[0:2]"); // 返回下标从0到2的元素 Assert.assertEquals(3, result.size()); Assert.assertSame(entities.get(0), result.get(0)); Assert.assertSame(entities.get(1), result.get(1)); Assert.assertSame(entities.get(2), result.get(1)); ``` -------------------------------- ### Validate InputStream JSON using JSONValidator in Java Source: https://github.com/alibaba/fastjson/wiki/JSONValidator This example illustrates validating JSON data from an InputStream using JSONValidator.fromUtf8(InputStream). The InputStream is expected to contain UTF8 encoded JSON data. ```java InputStream is = ...; JSONValidator validator = JSONValidator.fromUtf8(is); boolean valid = validator.validate(); ``` -------------------------------- ### Configure Fastjson SafeMode in Code (Java) Source: https://github.com/alibaba/fastjson/wiki/fastjson_safemode This snippet demonstrates how to enable Fastjson's SafeMode directly within your Java code by configuring the global parser instance. It's important to manage the `ParserConfig` instance correctly to avoid performance issues. ```java ParserConfig.getGlobalInstance().setSafeMode(true); ``` -------------------------------- ### Maven Dependency Configuration for Fastjson Source: https://github.com/alibaba/fastjson/wiki/Tutorial_cn This snippet shows how to add Fastjson as a dependency to your Maven project. Replace 'x.x.x' with the desired version number. This configuration is essential for including the Fastjson library in your Java project. ```xml com.alibaba fastjson x.x.x ``` -------------------------------- ### JSONPath Evaluation for Collection Properties (Java) Source: https://github.com/alibaba/fastjson/wiki/JSONPath This example shows how to use `JSONPath.eval` to extract a specific property (e.g., 'name') from multiple objects within a `List`. It demonstrates retrieving a list of names from a list of `Entity` objects. ```java List entities = new ArrayList(); entities.add(new Entity("wenshao")); entities.add(new Entity("ljw2083")); List names = (List)JSONPath.eval(entities, "$.name"); // 返回enties的所有名称 Assert.assertSame(entities.get(0).getName(), names.get(0)); Assert.assertSame(entities.get(1).getName(), names.get(1)); ```