Fastjson is an open source high-performance JSON library for serialization (generating JSON) and deserialization (parsing JSON) of Java objects. Here are the detailed usage guides:
1. Add dependencies
<dependency> <groupId></groupId> <artifactId>fastjson</artifactId> <version>2.0.39</version> <!-- Use the latest secure version --> </dependency>
2. Basic usage
2.1 Object to JSON (serialization)
import ; User user = new User("Zhang San", 25); String json = (user); // Output: {"name":"Zhang San","age":25}
2.2 JSON to object (deserialization)
String json = "{\"name\":\"Li Si\",\"age\":30}"; User user = (json, );
3. Common annotations
3.1 Field Control
public class User { @JSONField(name = "user_name") // Custom field name private String name; @JSONField(serialize = false) // Ignore fields private String password; @JSONField(format = "yyyy-MM-dd HH:mm:ss") // Date formatting private Date createTime; }
3.2 Serialization order
@JSONType(orders = {"id", "name", "age"}) // Specify the field orderpublic class User { private Long id; private String name; private Integer age; }
4. Advanced configuration
4.1 Global configuration
// Serialize configurationSerializeConfig config = new SerializeConfig(); (, new SimpleDateFormatSerializer("yyyy-MM-dd")); // Deserialize configurationParserConfig parserConfig = new ParserConfig(); (true); // Enable safe mode to prevent vulnerabilities String json = (obj, config); User user = (json, , parserConfig);
4.2 Custom serialization/deserialization
public class MoneySerializer implements ObjectSerializer { @Override public void write( JSONSerializer serializer, Object value, Object fieldName, Type fieldType, int features ) { BigDecimal amount = (BigDecimal) value; ((2) + "Yuan"); } } // Register a custom serializer().put(, new MoneySerializer());
5. Handle complex scenarios
5.1 Generic Collections
// SerializationList<User> users = (new User("Zhang San"), new User("Li Si")); String json = (users); // DeserializationList<User> parsedUsers = (json, );
5.2 Recycle reference processing
// Disable loop detection (on by default, may cause *)String json = (obj, );
5.3 Ignore unknown fields
User user = (json, , );
6. Performance optimization
6.1 Disable feature checking
// Improve serialization speed (sacrificing strict verification)String json = (obj, , );
6.2 Using JSONWriter to handle large files
try (JSONWriter writer = new JSONWriter(new FileWriter(""))) { (); for (User user : users) { (user); } (); }
7. Safety protection
7.1 Enable safe mode
().setSafeMode(true); // Deserialization of any class is prohibited
7.2 Whitelist Control
// Only deserialization of specified classes is allowed().addAccept(".");
8. Integrate with Spring
Replace Spring MVC default JSON processor
@Configuration public class WebConfig implements WebMvcConfigurer { @Override public void configureMessageConverters(List<HttpMessageConverter<?>> converters) { FastJsonHttpMessageConverter converter = new FastJsonHttpMessageConverter(); (fastJsonConfig()); (0, converter); } private FastJsonConfig fastJsonConfig() { FastJsonConfig config = new FastJsonConfig(); (); ("yyyy-MM-dd HH:mm:ss"); return config; } }
9. Frequently Asked Questions
9.1 Date format mismatch
// Global configuration date formatJSON.DEFFAULT_DATE_FORMAT = "yyyy-MM-dd"; String json = (new Date()); // Output "2023-01-01"
9.2 Field name case problem
// The hump turns underlined namingModel model = new Model(); ("test"); String json = (model, ); // Output {"user_name":"test"}
9.3 Handling Enum Types
public enum Status { @JSONField(name = "OK") // Custom enum value name SUCCESS, @JSONField(name = "ERR") FAILED } String json = (); // Output "OK"
10. Performance comparison suggestions
Scene | Recommended plan |
---|---|
High concurrency interface | Fastjson default configuration + safe mode |
Complex nested objects | Disable circular reference detection + cache configuration |
Handle oversized JSON files | Using JSONReader/JSONWriter |
Need strict type safety | Enable Safe Mode + Whitelist Control |
11. Things to note
- Version security: Always use the latest official version (Maven warehouse) to avoid historical loopholes.
- Data source: Be sure to enable Safe Mode or Whitelist when deserializing external inputs.
- Thread Safety: ParserConfig and SerializeConfig recommend global singletons.
- Compatibility: When using Fastjson with other JSON libraries, pay attention to annotation conflict issues.
Through reasonable configuration, Fastjson can process JSON data with near-limit performance, but it needs to make a trade-off between functionality, security, and performance.
This is the article about the newbie's guide to using Fastjson for JSON generation and parsing. For more related Fastjson to process JSON, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!