### Installation Source: https://context7.com/alibaba/fastjson2/llms.txt Instructions for adding FASTJSON 2 to your project using Maven or Gradle. ```APIDOC ## Installation ### Maven Core Library ```xml com.alibaba.fastjson2 fastjson2 2.0.61 ``` ### Gradle Core Library ```groovy dependencies { implementation 'com.alibaba.fastjson2:fastjson2:2.0.61' } ``` ### Fastjson v1 Compatibility Module Drop-in replacement for migrating from fastjson 1.2.x: ```xml com.alibaba fastjson 2.0.61 ``` ### Kotlin Module ```xml com.alibaba.fastjson2 fastjson2-kotlin 2.0.61 ``` ### Spring Framework Integration ```xml com.alibaba.fastjson2 fastjson2-extension-spring5 2.0.61 com.alibaba.fastjson2 fastjson2-extension-spring6 2.0.61 ``` ``` -------------------------------- ### Example Usage of encodeUTF8 Source: https://github.com/alibaba/fastjson2/wiki/fastjson_string_codec_methods This example demonstrates how to use the IOUtils.encodeUTF8 method. It shows conditional logic based on character encoding and the efficient use of the encodeUTF8 method to populate a byte array, avoiding extra array copying. ```java byte coder = UNSAFE.getObject(str, coderFieldOffset); byte[] value = UNSAFE.getObject(str, valueFieldOffset); if (coder == 0) { // ascii arraycopy } else { // ensureCapacity(chars.length * 3) byte[] bytes = ...; // int bytesLength = IOUtils.encodeUTF8(value, 0, value.length, bytes, bytesOffset); } ``` -------------------------------- ### JSON Input Example Source: https://github.com/alibaba/fastjson2/wiki/array_to_map_cn This is an example of a JSON input where the 'functions' field is an array. ```json { "functions":[ {"name": "concat", "category": ["Array","String"]}, {"name": "count", "category": "aggregate"}, {"name": "count", "category": "window"} ] } ``` -------------------------------- ### Example Usage of JDK 11 Fast String Creator Source: https://github.com/alibaba/fastjson2/wiki/fastjson_string_codec_methods Demonstrates how to use the `getStringCreatorJDK11` function to create a string efficiently from a byte array in JDK 11. Note: The example code provided in the source uses `Function` which seems to be a typo and should likely be `ToIntFunction` based on the method signature. ```java if (JDKUtils.JVM_VERSION == 11) { Function stringCreator = JDKUtils.getStringCreatorJDK11(); byte[] bytes = new byte[]{'a', 'b', 'c'}; String apply = stringCreator.apply(bytes); assertEquals("abc", apply); } ``` -------------------------------- ### Serialized JSON Output Example Source: https://github.com/alibaba/fastjson2/wiki/fastjson2_intro_cn This is an example of the JSON output generated from serializing a User object. ```json { "id" : 2, "name" : "FastJson2" } ``` -------------------------------- ### Example Usage of JDK 8 Fast String Creator Source: https://github.com/alibaba/fastjson2/wiki/fastjson_string_codec_methods Demonstrates how to use the `getStringCreatorJDK8` function to create a string efficiently from a character array in JDK 8. ```java if (JDKUtils.JVM_VERSION == 8) { BiFunction stringCreator = JDKUtils.getStringCreatorJDK8(); char[] chars = new char[]{'a', 'b', 'c'}; String apply = stringCreator.apply(chars, Boolean.TRUE); System.out.println(apply); } ``` -------------------------------- ### Using JDK 17 String Creator Source: https://github.com/alibaba/fastjson2/wiki/fastjson_string_codec_methods Demonstrates how to use the JDK 17 string creator function obtained via getStringCreatorJDK17. This example verifies the correct construction of a string from a byte array. ```java if (JDKUtils.JVM_VERSION == 17) { BiFunction stringCreator = JDKUtils.getStringCreatorJDK17(); byte[] bytes = new byte[]{'a', 'b', 'c'}; String apply = stringCreator.apply(bytes, StandardCharsets.US_ASCII); assertEquals("abc", apply); } ``` -------------------------------- ### Example Usage of encodeUTF8 Source: https://github.com/alibaba/fastjson2/wiki/fastjson_string_codec_methods Demonstrates how to use the `encodeUTF8` method by obtaining character data from a String using Unsafe and then encoding it. This approach avoids intermediate array copying for performance gains. ```java char[] chars = UNSAFE.getObject(str, valueFieldOffset); // ensureCapacity(chars.length * 3) byte[] bytes = ...; // int bytesLength = IOUtils.encodeUTF8(chars, 0, chars.length, bytes, bytesOffset); ``` -------------------------------- ### Implement ObjectWriter for InetAddress Serialization Source: https://github.com/alibaba/fastjson2/blob/main/docs/register_custom_reader_writer_en.md Example implementation of ObjectWriter for serializing InetAddress objects. It prioritizes using the host name for string representation. ```java class InetAddressWriter implements ObjectWriter { static final InetAddressWriter INSTANCE = new InetAddressWriter(); @Override public void write(JSONWriter jsonWriter, Object object, Object fieldName, Type fieldType, long features) { if (object == null) { jsonWriter.writeNull(); return; } InetAddress address = (InetAddress) object; // Prioritize using the name jsonWriter.writeString(address.getHostName()); } } ``` -------------------------------- ### Run Fastjson2 Benchmark with Different JDKs Source: https://github.com/alibaba/fastjson2/blob/main/docs/benchmark/benchmark_2.0.12.md Execute the Fastjson2 benchmark for the Eishay test case using different installed JDK versions. The classpath should point to the built benchmark JAR. ```shell ~/Install/jdk-1.8.0_341/bin/java -cp ~/git/fastjson2/benchmark/target/fastjson2-benchmarks.jar com.alibaba.fastjson2.benchmark.eishay.Eishay ``` ```shell ~/Install/jdk-11.0.16/bin/java -cp ~/git/fastjson2/benchmark/target/fastjson2-benchmarks.jar com.alibaba.fastjson2.benchmark.eishay.Eishay ``` ```shell ~/Install/jdk-17.0.4/bin/java -cp ~/git/fastjson2/benchmark/target/fastjson2-benchmarks.jar com.alibaba.fastjson2.benchmark.eishay.Eishay ``` ```shell ~/Install/jdk-18.0.2/bin/java -cp ~/git/fastjson2/benchmark/target/fastjson2-benchmarks.jar com.alibaba.fastjson2.benchmark.eishay.Eishay ``` -------------------------------- ### Configure Serialize Features with JSONField Source: https://github.com/alibaba/fastjson2/blob/main/docs/annotations_en.md Set serialization features using JSONField.serializeFeatures. This example demonstrates writing non-string numeric values as strings. ```java import com.alibaba.fastjson2.JSON; import com.alibaba.fastjson2.JSONWriter.Feature; import org.junit.jupiter.api.Test; @Test public void test() { Bean bean = new Bean(); bean.id = 100; assertEquals("{\"id\":\"100\"}", JSON.toJSONString(bean)); } public static class Bean { @JSONField(serializeFeatures = Feature.WriteNonStringValueAsString) public int id; } ``` -------------------------------- ### Implement Custom InetAddress Serialization Source: https://github.com/alibaba/fastjson2/wiki/register_custom_reader_writer_cn Example implementation of ObjectWriter for InetAddress. It serializes the address to its hostname string representation. Ensure the object is not null before processing. ```java class InetAddressWriter implements ObjectWriter { InetAddressWriter INSTANCE = new InetAddressWriter(); @Override public void write(JSONWriter jsonWriter, Object object, Object fieldName, Type fieldType, long features) { if (object == null) { jsonWriter.writeNull(); return; } InetAddress address = (InetAddress) object; // 优先使用name jsonWriter.writeString(address.getHostName()); } } ``` -------------------------------- ### Basic JSON Parsing and Serialization Source: https://github.com/alibaba/fastjson2/blob/main/README_cn.md This example demonstrates the fundamental usage of FASTJSON 2 for parsing a JSON string into a Java object and serializing a Java object back into a JSON string. It requires the `com.alibaba.fastjson2.JSON` import. ```java import com.alibaba.fastjson2.JSON; // 解析 User user = JSON.parseObject("{"name":"张三","age":25}", User.class); // 序列化 String json = JSON.toJSONString(user); ``` -------------------------------- ### Fastjson2 Performance Ranking Example Source: https://github.com/alibaba/fastjson2/blob/main/docs/benchmark/benchmark_2.0.12.md Illustrates the relative performance of Fastjson2 compared to Fastjson1, Jackson, and Gson for JSON string deserialization. The percentages indicate the performance relative to Fastjson2. ```java // ecs.c7.xlarge-oracle-jdk1.8.0_341_x64 fastjson2 > fastjson1 > jackson > gson 100% 76.16% 41.62% 34.44% ``` -------------------------------- ### JSONPath Examples: Direct and Bracket Notation Source: https://github.com/alibaba/fastjson2/blob/main/docs/JSONPath/jsonpath_cn.md Demonstrates equivalent ways to access nested JSON properties using direct dot notation and bracket notation with string keys. Useful for accessing specific fields in a JSON structure. ```java $.store.book[0].title ``` ```java $['store']['book'][0]['title'] ``` -------------------------------- ### Implement Custom Instant Deserialization Source: https://github.com/alibaba/fastjson2/wiki/register_custom_reader_writer_cn Example implementation of ObjectReader for Instant. It reads a long value representing milliseconds since the epoch and converts it to an Instant object. Handles null values. ```java import java.time.Instant; import com.alibaba.fastjson2.reader.ObjectReader; class InstantReader implements ObjectReader { public static final InstantReader INSTANCE = new InstantReader(); @Override public Object readObject(JSONReader jsonReader, Type fieldType, Object fieldName, long features) { if (jsonReader.nextIfNull()) { return null; } long millis = jsonReader.readInt64Value(); return Instant.ofEpochMilli(millis); } } ``` -------------------------------- ### String Value Benchmark Results Source: https://github.com/alibaba/fastjson2/wiki/fastjson_string_codec_methods A comparison of performance between using reflection and Unsafe to get the String's value array. Unsafe shows significantly higher throughput. ```java Benchmark Mode Cnt Score Error Units StringGetValueBenchmark.reflect thrpt 5 438374.685 ± 1032.028 ops/ms StringGetValueBenchmark.unsafe thrpt 5 1302654.150 ± 59169.706 ops/ms ``` -------------------------------- ### Get String Value and Coder via Unsafe Source: https://github.com/alibaba/fastjson2/wiki/fastjson_string_codec_methods This example shows how to use Unsafe to retrieve both the 'value' field (as a byte array) and the 'coder' field from a String object. This is relevant for JDK 9+ String implementations. ```java static long valueFieldOffset; static long coderFieldOffset; static { try { Field valueField = String.class.getDeclaredField("value"); valueFieldOffset = UNSAFE.objectFieldOffset(valueField); Field coderField = String.class.getDeclaredField("coder"); coderFieldOffset = UNSAFE.objectFieldOffset(coderField); } catch (NoSuchFieldException ignored) {} } //////////////////////////////////////////// byte coder = UNSAFE.getObject(str, coderFieldOffset); byte[] bytes = (byte[]) UNSAFE.getObject(str, valueFieldOffset); ``` -------------------------------- ### Configure Fastjson2 JIT via JVM Arguments Source: https://github.com/alibaba/fastjson2/wiki/jit_optimization Use JVM startup parameters to globally configure Fastjson2's JIT features. This is useful for system-wide performance tuning. ```sh -Dfastjson2.features=disableReferenceDetect,disableArrayMapping,disableJSONB,disableAutoType,disableSmartMatch ``` -------------------------------- ### Standard Project Build Source: https://github.com/alibaba/fastjson2/blob/main/CONTRIBUTING.md Build the project using the Maven wrapper. This command cleans the project and packages it. ```bash ./mvnw clean package ``` -------------------------------- ### Build with Javadoc and Dokka Source: https://github.com/alibaba/fastjson2/blob/main/CONTRIBUTING.md Build the project while also generating Javadoc and Dokka documentation. Use --no-transfer-progress for cleaner output. ```bash ./mvnw -V --no-transfer-progress -Pgen-javadoc -Pgen-dokka clean package ``` -------------------------------- ### Get String Value via Unsafe (char array) Source: https://github.com/alibaba/fastjson2/wiki/fastjson_string_codec_methods This code uses the Unsafe API to get the 'value' field offset and then retrieve the character array from a String object. This is generally faster than reflection. ```java static long valueFieldOffset; static { try { Field valueField = String.class.getDeclaredField("value"); valueFieldOffset = UNSAFE.objectFieldOffset(valueField); } catch (NoSuchFieldException ignored) {} } //////////////////////////////////////////// char[] chars = (char[]) UNSAFE.getObject(str, valueFieldOffset); ``` -------------------------------- ### Configure Maven Settings for Central Repository Source: https://github.com/alibaba/fastjson2/blob/main/docs/maven_deploy_guide.md Configure your Maven settings.xml with your Sonatype account credentials to allow deployment to the central repository. Replace __YOUR_USERNAME__ and __YOUR_PASSWORD__ with your actual credentials. ```xml central __YOUR_USERNAME__ __YOUR_PASSWORD__ ``` -------------------------------- ### Define Kotlin User Class Source: https://github.com/alibaba/fastjson2/blob/main/docs/Kotlin/kotlin_en.md Example of a simple Kotlin data class used for parsing JSON data. ```kotlin class User( var id: Int, var name: String ) ``` -------------------------------- ### Get Simple Property from JSONObject Source: https://github.com/alibaba/fastjson2/blob/main/docs/Kotlin/kotlin_en.md Retrieves simple property values (like Int or String) from a JSONObject by key. ```kotlin val text = "" val data = JSON.parseObject(text) // JSONObject val id = data.getIntValue("id") // Int val name = data.getString("name") // String ``` -------------------------------- ### Clone and Build Fastjson2 Project Source: https://github.com/alibaba/fastjson2/blob/main/docs/benchmark/benchmark_2.0.12.md Clone the Fastjson2 repository, checkout a specific version, and build the project using Maven. Ensure tests are skipped during the build process. ```shell git clone https://github.com/alibaba/fastjson2 cd fastjson2 git checkout 2.0.12 mvn clean install -Dmaven.test.skip ``` -------------------------------- ### Get Simple Properties from JSONArray in Java Source: https://github.com/alibaba/fastjson2/wiki/fastjson2_intro_cn Retrieves primitive values from a JSONArray by index. Ensure the `com.alibaba.fastjson2` package is imported. ```java String text = "[2, "fastjson2"]"; JSONArray array = JSON.parseArray(text); int id = array.getIntValue(0); String name = array.getString(1); ``` -------------------------------- ### Clone Repository and Run Benchmark Source: https://github.com/alibaba/fastjson2/wiki/fastjson2_vs_simdjson This script clones the Fastjson2 repository, checks out a specific commit, sets the JAVA_HOME environment variable, builds the project, and then runs the SchemaBasedParseAndSelectBenchmark. ```shell git clone https://github.com/alibaba/fastjson2.git cd fastjson2 git checkout c17a8d4a0d7209b4eff29026ea2827b5f5aba822 export JAVA_HOME=~/Install/jdk21 ./mvnw clean install -Dmaven.test.skip ~/Install/jdk21/bin/java -cp ~/git/fastjson2/benchmark_21/target/fastjson2-benchmarks.jar com.alibaba.fastjson2.benchmark.simdjson.SchemaBasedParseAndSelectBenchmark ``` -------------------------------- ### Get Simple Properties from JSONObject in Java Source: https://github.com/alibaba/fastjson2/wiki/fastjson2_intro_cn Retrieves primitive values from a JSONObject by key. Ensure the `com.alibaba.fastjson2` package is imported. ```java String text = "{"id": 2,"name": "fastjson2"}"; JSONObject obj = JSON.parseObject(text); int id = obj.getIntValue("id"); String name = obj.getString("name"); ``` -------------------------------- ### Get Simple Properties from JSONObject (Java) Source: https://github.com/alibaba/fastjson2/blob/main/README.md Retrieves primitive integer and string values from a JSONObject using `getIntValue` and `getString` methods. ```java String text = "{"id": 2, "name": "fastjson2"}"; JSONObject obj = JSON.parseObject(text); int id = obj.getIntValue("id"); String name = obj.getString("name"); ``` -------------------------------- ### Clone and Build Fastjson2 Source: https://github.com/alibaba/fastjson2/wiki/fastjson_benchmark Clone the Fastjson2 repository, checkout a specific version, and build the project. Ensure to skip tests during the build process. ```shell git clone https://github.com/alibaba/fastjson2 cd fastjson2 git checkout 2.0.38 mvn clean install -Dmaven.test.skip ``` -------------------------------- ### Maven Repository Configuration Source: https://github.com/alibaba/fastjson2/blob/main/fastjson1-compatible/src/test/resources/1.txt Configure your Maven settings.xml to include the Alibaba OpenSource repository for Fastjson. ```xml opensesame Alibaba OpenSource Repsoitory http://code.alibabatech.com/mvn/releases/ false ``` -------------------------------- ### Standard Test Execution Source: https://github.com/alibaba/fastjson2/blob/main/CONTRIBUTING.md Run all standard tests for the project using the Maven wrapper. ```bash ./mvnw clean test ``` -------------------------------- ### Get Bean Object from JSONArray/JSONObject (Including Generic) Source: https://github.com/alibaba/fastjson2/blob/main/docs/Kotlin/kotlin_en.md Extracts a generic type (like List) from a JSONArray or JSONObject, using the `into` method. ```kotlin val obj = ... // JSONObject val array = ... // JSONArray val user = array.into>(0) val user = obj.into>("key") ``` -------------------------------- ### Build and Test fastjson2 Source: https://github.com/alibaba/fastjson2/blob/main/AGENTS.md Standard Maven commands for building, testing, and validating the fastjson2 project. Ensure all checks pass before submitting pull requests. ```bash mvn clean package # build all ``` ```bash mvn test # run tests ``` ```bash mvn validate # checkstyle + modernizer checks ``` -------------------------------- ### Get Simple Properties from JSONArray (Java) Source: https://github.com/alibaba/fastjson2/blob/main/README.md Retrieves primitive integer and string values from a JSONArray by index using `getIntValue` and `getString` methods. ```java String text = "[2, \"fastjson2\"]"; JSONArray array = JSON.parseArray(text); int id = array.getIntValue(0); String name = array.getString(1); ``` -------------------------------- ### Run Fastjson2 Benchmark with JDK 17 Source: https://github.com/alibaba/fastjson2/wiki/fastjson_benchmark Execute the Eishay benchmark test using Java 17. This command requires the benchmark JAR to be built and available in the specified path. ```shell ~/Install/jdk17/bin/java -cp ~/git/fastjson2/benchmark/target/fastjson2-benchmarks.jar com.alibaba.fastjson2.benchmark.eishay.Eishay ``` -------------------------------- ### Object Type Representation in Fastjson2 Source: https://github.com/alibaba/fastjson2/blob/main/docs/JSONB/jsonb_format_en.md Defines the byte-prefix structure for object types, starting with 0xa6 and ending with 0xa5, enclosing key-value pairs. ```java 0xa6 [ ]... 0xa5 ``` -------------------------------- ### JDK 8 String Creation Benchmark Results Source: https://github.com/alibaba/fastjson2/wiki/fastjson_string_codec_methods Performance comparison of different string creation methods in JDK 8, showing significant speed improvements for optimized methods over the standard 'new String()'. ```plsql Benchmark Mode Cnt Score Error Units StringCreateBenchmark.invoke thrpt 5 784869.350 ± 1936.754 ops/ms StringCreateBenchmark.langAccess thrpt 5 784029.186 ± 2734.300 ops/ms StringCreateBenchmark.unsafe thrpt 5 761176.319 ± 11914.549 ops/ms StringCreateBenchmark.newString thrpt 5 140883.533 ± 2217.773 ops/ms ``` -------------------------------- ### Get JavaBean from JSONArray/JSONObject (Java) Source: https://github.com/alibaba/fastjson2/blob/main/README.md Retrieve a JavaBean object from a JSONArray at a specific index or from a JSONObject using a key. Ensure the User class is defined. ```java JSONArray array = ...; JSONObject obj = ...; User user = array.getObject(0, User.class); User user = obj.getObject("key", User.class); ``` -------------------------------- ### Configure Ignored Fields with @JSONType(ignores) Source: https://github.com/alibaba/fastjson2/blob/main/docs/annotations_en.md Use the @JSONType(ignores) annotation to specify fields that should be ignored during serialization. The example shows how to exclude 'id2' and 'id3'. ```java @JSONType(ignores = {"id2", "id3"}) public static class Bean { public int getId() { return 101; } public int getId2() { return 102; } public int getId3() { return 103; } } ``` -------------------------------- ### Download Fastjson JAR Source: https://github.com/alibaba/fastjson2/blob/main/fastjson1-compatible/src/test/resources/1.txt Direct download links for the Fastjson JAR and source JAR if not using Maven. ```html http://code.alibabatech.com/mvn/releases/com/alibaba/fastjson/1.0.4/fastjson-1.0.4.jar ``` ```html http://code.alibabatech.com/mvn/releases/com/alibaba/fastjson/1.0.4/fastjson-1.0.4-sources.jar ``` -------------------------------- ### Benchmark Results on Aliyun c8i Source: https://github.com/alibaba/fastjson2/wiki/fastjson2_vs_simdjson Benchmark results for the 'countUniqueUsersWithDefaultProfile' operation on Aliyun c8i instances, comparing Fastjson2 with Jackson and simdjson. ```text Benchmark Mode Cnt Score Error Units countUniqueUsersWithDefaultProfile_fastjson thrpt 5 4.632 ? 0.009 ops/ms countUniqueUsersWithDefaultProfile_jackson thrpt 5 1.056 ? 0.003 ops/ms countUniqueUsersWithDefaultProfile_simdjson thrpt 5 3.863 ? 0.032 ops/ms countUniqueUsersWithDefaultProfile_simdjsonPadded thrpt 5 4.121 ? 0.012 ops/ms countUniqueUsersWithDefaultProfile_wast thrpt 5 4.887 ? 0.014 ops/ms ``` -------------------------------- ### Enable AutoType Safely with Scoped Filter Source: https://github.com/alibaba/fastjson2/blob/main/docs/FAQ_en.md Use AutoTypeFilter with a narrow whitelist to enable AutoType safely. This example restricts allowed classes to the 'com.mycompany.model' package. ```java // Preferred: scoped filter with narrow whitelist Filter autoTypeFilter = JSONReader.autoTypeFilter( "com.mycompany.model" // Only allow classes in this package ); Object result = JSON.parseObject(json, Object.class, autoTypeFilter); ``` -------------------------------- ### Benchmark Results on Aliyun c8a Source: https://github.com/alibaba/fastjson2/wiki/fastjson2_vs_simdjson Benchmark results for the 'countUniqueUsersWithDefaultProfile' operation on Aliyun c8a instances, comparing Fastjson2 with Jackson and simdjson. ```text Benchmark Mode Cnt Score Error Units countUniqueUsersWithDefaultProfile_fastjson thrpt 5 5.156 ? 0.170 ops/ms countUniqueUsersWithDefaultProfile_jackson thrpt 5 1.168 ? 0.018 ops/ms countUniqueUsersWithDefaultProfile_simdjson thrpt 5 3.721 ? 0.071 ops/ms countUniqueUsersWithDefaultProfile_simdjsonPadded thrpt 5 3.850 ? 0.056 ops/ms countUniqueUsersWithDefaultProfile_wast thrpt 5 5.313 ? 0.076 ops/ms ``` -------------------------------- ### Get Bean Object from JSONArray/JSONObject (No Generic) Source: https://github.com/alibaba/fastjson2/blob/main/docs/Kotlin/kotlin_en.md Extracts a specific object from a JSONArray by index or from a JSONObject by key, converting it to a specified Kotlin type without generics. ```kotlin val obj = ... // JSONObject val array = ... // JSONArray val user = array.to(0) val user = obj.to("key") ``` -------------------------------- ### Run Fastjson2 Benchmark with JDK 8 Source: https://github.com/alibaba/fastjson2/wiki/fastjson_benchmark Execute the Eishay benchmark test using Java 8. This command requires the benchmark JAR to be built and available in the specified path. ```shell ~/Install/jdk8/bin/java -cp ~/git/fastjson2/benchmark/target/fastjson2-benchmarks.jar com.alibaba.fastjson2.benchmark.eishay.Eishay ``` -------------------------------- ### Get String Value via Reflection Source: https://github.com/alibaba/fastjson2/wiki/fastjson_string_codec_methods This snippet demonstrates how to obtain the 'value' field of a String object using Java reflection. It requires setting the field to be accessible. ```java static Field valueField; static { try { valueField = String.class.getDeclaredField("value"); valueField.setAccessible(true); } catch (NoSuchFieldException ignored) {} } //////////////////////////////////////////// char[] chars = (char[]) valueField.get(str); ``` -------------------------------- ### Run Fastjson2 Benchmark with GraalVM 17 Source: https://github.com/alibaba/fastjson2/wiki/fastjson_benchmark Execute the Eishay benchmark test using GraalVM 17. This command requires the benchmark JAR to be built and available in the specified path. ```shell ~/Install/graalvm-17/bin/java -cp ~/git/fastjson2/benchmark/target/fastjson2-benchmarks.jar com.alibaba.fastjson2.benchmark.eishay.Eishay ``` -------------------------------- ### Run Fastjson2 JMH benchmarks Source: https://github.com/alibaba/fastjson2/blob/main/docs/performance_cn.md Fastjson2 includes JMH benchmarks in the 'benchmark/' module. Navigate to the directory and run the benchmarks using Maven. ```bash cd benchmark mvn clean package java -jar target/benchmarks.jar ``` -------------------------------- ### Get JavaBean from JSONArray/JSONObject (Kotlin) Source: https://github.com/alibaba/fastjson2/blob/main/README.md Retrieve a JavaBean object from a JSONArray at a specific index or from a JSONObject using a key using extension functions. Ensure the User class is defined. ```kotlin val array: JSONArray = ... val obj: JSONObject = ... val user = array.to(0) val user = obj.to("key") ``` -------------------------------- ### Run Fastjson2 Benchmark with JDK 11 Source: https://github.com/alibaba/fastjson2/wiki/fastjson_benchmark Execute the Eishay benchmark test using Java 11. This command requires the benchmark JAR to be built and available in the specified path. ```shell ~/Install/jdk11/bin/java -cp ~/git/fastjson2/benchmark/target/fastjson2-benchmarks.jar com.alibaba.fastjson2.benchmark.eishay.Eishay ``` -------------------------------- ### Recommended JVM parameters for performance Source: https://github.com/alibaba/fastjson2/blob/main/docs/performance_cn.md These JVM parameters can enhance performance. CompactStrings is enabled by default on JDK 9+, and the Vector API incubator module needs to be explicitly added for JDK 17+. ```bash # Enable compact strings (JDK 9+, enabled by default) -XX:+CompactStrings # JDK 17+, enable Vector API incubator module --add-modules jdk.incubator.vector ``` -------------------------------- ### Basic JSON Serialization with Features Source: https://github.com/alibaba/fastjson2/blob/main/docs/features_en.md Demonstrates basic JSON serialization with the 'WriteNulls' feature. Multiple features can be combined for customized output. ```java User user = new User("John", 25, null); String json = JSON.toJSONString(user, JSONWriter.Feature.WriteNulls); ``` ```java String json2 = JSON.toJSONString(user, JSONWriter.Feature.WriteNulls, JSONWriter.Feature.PrettyFormat); ``` ```java String json3 = JSON.toJSONString(user, JSONWriter.Feature.BeanToArray); ``` -------------------------------- ### Deploy FASTJSON2 to Maven Central Source: https://github.com/alibaba/fastjson2/blob/main/docs/maven_deploy_guide.md Execute the Maven wrapper to clean the project and deploy the release artifacts to the Maven Central repository. The -DperformRelease flag is crucial for this operation. ```bash ./mvnw clean && ./mvnw deploy -DperformRelease ``` -------------------------------- ### Clone FASTJSON 2 Repository Source: https://github.com/alibaba/fastjson2/blob/main/CONTRIBUTING.md Clone your forked repository and navigate into the project directory. ```bash git clone https://github.com//fastjson2.git cd fastjson2 ``` -------------------------------- ### JSON String Deserialization Example Source: https://github.com/alibaba/fastjson2/wiki/fastjson_benchmark This snippet demonstrates the common use case of deserializing a JSON string into a Java Bean object using Fastjson2's parseJSONObject method. This is a primary scenario for performance testing. ```java String str = "..."; Bean bean = JSON.parseJSONObject(str, Bean.class); ``` -------------------------------- ### Configure JSONReader/JSONWriter Features with @JSONType Source: https://github.com/alibaba/fastjson2/blob/main/docs/annotations_en.md Utilize @JSONType(deserializeFeatures = ...) and @JSONType(serializeFeatures = ...) to configure specific features for JSON reading and writing. The example demonstrates trimming strings on deserialize and writing nulls on serialize. ```java @Slf4j public class JSONTypeFeatures { // Trim the string when serialize // Fields that output null when deserialize @JSONType(deserializeFeatures = JSONReader.Feature.TrimString, serializeFeatures = JSONWriter.Feature.WriteNulls) public static class OrdersBean { public String filed1; public String filed2; } @Test public void test() { OrdersBean bean = new OrdersBean(); bean.filed1 = "fastjson2"; log.info(JSON.toJSONString(bean)); //{"filed1":"fastjson2","filed2":null} String json="{\"filed1\":\" fastjson2 \",\"filed2\":\"2\"}"; OrdersBean bean2 = JSON.parseObject(json, OrdersBean.class); log.info(bean2.filed1); //fastjson2 } } ``` -------------------------------- ### Build Specific Module Source: https://github.com/alibaba/fastjson2/blob/main/CONTRIBUTING.md Build only the 'core' module for faster iteration during development. ```bash ./mvnw -pl core clean package ``` -------------------------------- ### Benchmark Results on AWS c5.xlarge Source: https://github.com/alibaba/fastjson2/wiki/fastjson2_vs_simdjson Benchmark results for the 'countUniqueUsersWithDefaultProfile' operation on AWS c5.xlarge instances, comparing Fastjson2 with Jackson and simdjson. ```text Benchmark Mode Cnt Score Error Units countUniqueUsersWithDefaultProfile_fastjson thrpt 5 3.414 ? 0.007 ops/ms countUniqueUsersWithDefaultProfile_jackson thrpt 5 0.697 ? 0.001 ops/ms countUniqueUsersWithDefaultProfile_simdjson thrpt 5 2.146 ? 0.004 ops/ms countUniqueUsersWithDefaultProfile_simdjsonPadded thrpt 5 2.235 ? 0.082 ops/ms countUniqueUsersWithDefaultProfile_wast thrpt 5 3.740 ? 0.007 ops/ms ``` -------------------------------- ### Specify Field Order with @JSONType(orders) Source: https://github.com/alibaba/fastjson2/blob/main/docs/annotations_en.md Use the @JSONType(orders = {"filed1", "filed2"}) annotation to explicitly define the order of fields during JSON serialization. The example specifies a custom order for four fields. ```java @Slf4j public class JSONTypeOrders { @JSONType(orders = {"filed4", "filed3", "filed2", "filed1"}) public static class OrdersBean { public String filed1; public String filed2; public String filed3; public String filed4; } @Test public void test() { OrdersBean bean = new OrdersBean(); bean.filed1 = "1"; bean.filed2 = "2"; bean.filed3 = "3"; bean.filed4 = "4"; log.info(JSON.toJSONString(bean)); //{"filed4":"4","filed3":"3","filed2":"2","filed1":"1"} } } ``` -------------------------------- ### Evaluate JSONPath on Entity Properties Source: https://github.com/alibaba/fastjson2/blob/main/docs/JSONPath/jsonpath_en.md Demonstrates evaluating JSONPath expressions on a custom Entity object. Use `JSONPath.eval` to get property values and `JSONPath.contains` to check for property existence. Asserts expected values using `assertSame`, `assertTrue`, and `assertEquals`. ```java public void test_entity() throws Exception { Entity entity = new Entity(123, new Object()); assertSame(entity.getValue(), JSONPath.eval(entity, "$.value")); assertTrue(JSONPath.contains(entity, "$.value")); assertEquals(2, JSONPath.eval(entity, "$.length()")); assertEquals(0, JSONPath.eval(new Object[0], "$.length()")); } ``` ```java 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; } } ``` -------------------------------- ### Serialize and Deserialize with JSONB Source: https://context7.com/alibaba/fastjson2/llms.txt Illustrates using JSONB for high-performance binary JSON serialization and deserialization. Covers standard serialization, deserialization, compact serialization using BeanToArray feature, and parsing compact formats. ```java import com.alibaba.fastjson2.JSONB; import com.alibaba.fastjson2.JSONReader; import com.alibaba.fastjson2.JSONWriter; public class Message { public long id; public String content; public String[] tags; public long timestamp; public Message() {} public Message(long id, String content, String[] tags) { this.id = id; this.content = content; this.tags = tags; this.timestamp = System.currentTimeMillis(); } } // Serialize to JSONB binary format Message message = new Message(1001, "Hello World", new String[]{"greeting", "test"}); byte[] jsonbBytes = JSONB.toBytes(message); System.out.println("JSONB size: " + jsonbBytes.length + " bytes"); // Deserialize from JSONB Message restored = JSONB.parseObject(jsonbBytes, Message.class); System.out.println(restored.content); // "Hello World" // Even more compact with BeanToArray feature (serializes as array instead of object) byte[] compactBytes = JSONB.toBytes(message, JSONWriter.Feature.BeanToArray); System.out.println("Compact JSONB size: " + compactBytes.length + " bytes"); // Parse compact format Message fromCompact = JSONB.parseObject(compactBytes, Message.class, JSONReader.Feature.SupportArrayToBean); // Compare sizes String jsonText = JSON.toJSONString(message); System.out.println("JSON text size: " + jsonText.getBytes().length + " bytes"); System.out.println("JSONB size: " + jsonbBytes.length + " bytes"); System.out.println("JSONB compact size: " + compactBytes.length + " bytes"); // JSONB with type information for polymorphic types byte[] typedBytes = JSONB.toBytes(message, JSONWriter.Feature.WriteClassName); Object obj = JSONB.parseObject(typedBytes, Object.class, JSONReader.Feature.SupportAutoType); ``` -------------------------------- ### Eishay Performance Benchmark Results (JDK 8) Source: https://github.com/alibaba/fastjson2/blob/main/docs/benchmark_en.md Benchmark results for Fastjson2, Fastjson1, and Jackson on MacOS M1 Max with ARM Zulu JDK 8. Shows performance in operations per millisecond for different parsing scenarios. ```text Benchmark Mode Cnt Score Error Units EishayParseTreeString.fastjson2 thrpt 5 1297.637 ± 14.343 ops/ms EishayParseTreeString.fastjson1 thrpt 5 649.525 ± 2.845 ops/ms EishayParseTreeString.jackson thrpt 5 701.278 ± 17.552 ops/ms EishayParseTreeUTF8Bytes.fastjson2 thrpt 5 1059.120 ± 17.679 ops/ms EishayParseTreeUTF8Bytes.fastjson1 thrpt 5 654.592 ± 3.706 ops/ms EishayParseTreeUTF8Bytes.jackson thrpt 5 825.801 ± 3.161 ops/ms EishayParseString.fastjson2 thrpt 5 2057.589 ± 9.382 ops/ms EishayParseString.fastjson1 thrpt 5 1588.114 ± 4.540 ops/ms EishayParseString.jackson thrpt 5 718.630 ± 14.570 ops/ms EishayParseStringPretty.fastjson2 thrpt 5 1519.731 ± 108.501 ops/ms EishayParseStringPretty.fastjson1 thrpt 5 441.860 ± 12.675 ops/ms EishayParseStringPretty.jackson thrpt 5 659.436 ± 14.518 ops/ms EishayParseUTF8Bytes.fastjson2 thrpt 5 1580.093 ± 11.714 ops/ms EishayParseUTF8Bytes.fastjson1 thrpt 5 1488.098 ± 7.587 ops/ms EishayParseUTF8Bytes.jackson thrpt 5 973.172 ± 4.252 ops/ms EishayParseUTF8BytesPretty.fastjson2 thrpt 5 1623.723 ± 5.420 ops/ms EishayParseUTF8BytesPretty.fastjson1 thrpt 5 434.529 ± 1.160 ops/ms EishayParseUTF8BytesPretty.jackson thrpt 5 861.123 ± 2.946 ops/ms ``` -------------------------------- ### JDK 8 Fast String Creation using LambdaMetafactory Source: https://github.com/alibaba/fastjson2/wiki/fastjson_string_codec_methods This method uses MethodHandles.Lookup and LambdaMetafactory to bind to the non-public String constructor, enabling fast string creation in JDK 8. Requires setting MethodHandles.Lookup to TRUSTED. ```java public static BiFunction getStringCreatorJDK8() throws Throwable { Constructor constructor = MethodHandles.Lookup.class.getDeclaredConstructor(Class.class, int.class); constructor.setAccessible(true); MethodHandles lookup = constructor.newInstance( String.class , -1 // Lookup.TRUSTED ); MethodHandles.Lookup caller = lookup.in(String.class); MethodHandle handle = caller.findConstructor( String.class, MethodType.methodType(void.class, char[].class, boolean.class) ); CallSite callSite = LambdaMetafactory.metafactory( caller , "apply" , MethodType.methodType(BiFunction.class) , handle.type().generic() , handle , handle.type() ); return (BiFunction) callSite.getTarget().invokeExact(); } ``` -------------------------------- ### Parse String to Tree Benchmark (JDK 17) Source: https://github.com/alibaba/fastjson2/wiki/benchmark_2.0.7_aarch64 Compares Fastjson1, Fastjson2, and Jackson performance when parsing a string to a tree structure in a JDK 17 environment. Results are measured in operations per millisecond. ```text Benchmark Mode Cnt Score Error Units EishayParseTreeString.fastjson1 thrpt 5 868.541 ± 2.946 ops/ms EishayParseTreeString.fastjson2 thrpt 5 1289.000 ± 11.511 ops/ms EishayParseTreeString.jackson thrpt 5 803.867 ± 4.779 ops/ms ``` -------------------------------- ### Basic JSON Deserialization with Features Source: https://github.com/alibaba/fastjson2/blob/main/docs/features_en.md Shows basic JSON deserialization with the 'SupportSmartMatch' feature. Multiple features can be combined for customized parsing. ```java String json = "{\"name\":\"John\",\"age\":25}"; User user = JSON.parseObject(json, User.class, JSONReader.Feature.SupportSmartMatch); ``` ```java User user2 = JSON.parseObject(json, User.class, JSONReader.Feature.SupportSmartMatch, JSONReader.Feature.InitStringFieldAsEmpty); ``` -------------------------------- ### Parse String to Tree Benchmark (JDK 8) Source: https://github.com/alibaba/fastjson2/wiki/benchmark_2.0.7_aarch64 Compares Fastjson1, Fastjson2, and Jackson performance when parsing a string to a tree structure in a JDK 8 environment. Results are measured in operations per millisecond. ```text Benchmark Mode Cnt Score Error Units EishayParseTreeString.fastjson1 thrpt 5 689.334 ± 4.869 ops/ms EishayParseTreeString.fastjson2 thrpt 5 1354.274 ± 5.955 ops/ms EishayParseTreeString.jackson thrpt 5 775.679 ± 3.524 ops/ms ``` -------------------------------- ### JDK 17 String Construction with MethodHandles Source: https://github.com/alibaba/fastjson2/wiki/fastjson_string_codec_methods This method utilizes MethodHandles and LambdaMetafactory to create a BiFunction for efficient string construction from byte arrays and Charset in JDK 17. Requires JVM argument --add-opens java.base/java.lang.invoke=ALL-UNNAMED. ```java public static BiFunction getStringCreatorJDK17() throws Throwable { Constructor constructor = MethodHandles.Lookup.class.getDeclaredConstructor(Class.class, Class.class, int.class); constructor.setAccessible(true); MethodHandles.Lookup lookup = constructor.newInstance( String.class , null , -1 // Lookup.TRUSTED ); MethodHandles.Lookup caller = lookup.in(String.class); MethodHandle handle = caller.findStatic( String.class, "newStringNoRepl1", MethodType.methodType(String.class, byte[].class, Charset.class) ); CallSite callSite = LambdaMetafactory.metafactory( caller , "apply" , MethodType.methodType(BiFunction.class) , handle.type().generic() , handle , handle.type() ); return (BiFunction) callSite.getTarget().invokeExact(); } ```