Comprehensive Guide to JSON Conversion Using Fastjson in Java
This article provides a detailed tutorial on JSON fundamentals and demonstrates how to convert between Java objects, collections, maps, and JSON strings or objects using Alibaba's fastjson library, covering key‑value and array structures, code examples, and practical conversion scenarios.
Preface
JSON is a subset of JavaScript data types, and because mainstream browsers use a common JavaScript engine, JSON parsing enjoys excellent compatibility. This is the origin of the name "JavaScript Object Notation" (JSON).
The article classifies input and output result types into two major categories: converting other types to JSON and converting JSON to other types.
Note: All examples are based on Alibaba's fastjson library.
fastjson can boost JSON parsing performance to the extreme and is currently the fastest JSON library for Java. Its simple API is widely used in cache serialization, protocol interaction, web output, Android clients, and many other scenarios.
<!-- https://mvnrepository.com/artifact/com.alibaba/fastjson -->
com.alibaba
fastjson
1.2.831. JSON Review
Before diving into the main content, we briefly review the basic concepts of JSON.
1.1 Structure Forms
JSON has two structural forms: a key‑value pair form and an array form.
Example of a key‑value pair JSON:
{
"playerInfo": {
"playerName": "Alex",
"playerAge": 18
},
"activityId": "871047729944117248",
"activityType": "OA",
"awardId": "886982449056579584",
"awardName": "OA测试",
"stageId": "816982449034752351",
"roundId": "808657473445768946",
"noticeTypes": "APP"
}This structure is an unordered collection of "key":"value" pairs, enclosed by curly braces. Keys are followed by a colon, pairs are separated by commas, and objects can be nested.
Example of an array‑form JSON:
{
"data": {
"content": [
{
"id": "926160574061371392",
"status": "PROGRESSING",
"updateContent": "测试一下",
"version": "10.6.0",
"createTime": "2023-10-31 17:11:28"
},
{
"id": "926160574061371326",
"status": "CANCELED",
"updateContent": "测试测试",
"version": "123.0",
"createTime": "2023-10-31 17:11:28"
}
],
"code": 200,
"msg": "成功",
"success": true
}
}An array form is an ordered collection of values, enclosed by square brackets, with values separated by commas.
2. Other Types → JSON
Other types include Java objects, arrays, strings, generic types, and generic Object instances; JSON‑related types refer to JsonObject, Json strings, etc.
2.1 JavaBean to JsonObject
Entity class example:
@Data
@EqualsAndHashCode(callSuper = true) // generate equals() and hashCode() and allow superclass fields
public class Computer extends BaseEntity {
/** Central Processing Unit */
private String cpu;
/** Memory */
private String memory;
/** GPU */
private String gpu;
/** SSD */
private String ssd;
}Implementation example:
@Test
public void javaBeanToJsonObject() {
Computer computer = new Computer();
computer.setCpu("r7-4800h");
computer.setGpu("RTX-3060");
computer.setSsd("512GB");
computer.setMemory("32GB");
JSONObject jsonObject = (JSONObject) JSONObject.toJSON(computer);
log.info("------Result: {} Type: {}------", jsonObject, jsonObject.getClass());
}Result screenshot omitted for brevity.
2.2 JavaBean to Json String
@Test
public void javaBeanToJsonString() {
Computer computer = new Computer();
computer.setCpu("r7-4800h");
computer.setGpu("RTX-3060");
computer.setSsd("512GB");
computer.setMemory("32GB");
String jsonStr = JSON.toJSONString(computer);
log.info("------Result: {} Type: {}------", jsonStr, jsonStr.getClass());
}Result screenshot omitted.
2.3 List to JsonArray
@Test
public void listToJsonArray() {
List
list = computerService.list();
JSONArray jsonArray = (JSONArray) JSONArray.toJSON(list);
log.info("------Element 0: {} Type: {}------", jsonArray.get(0), jsonArray.getClass());
log.info("------Element 1: {} Type: {}------", jsonArray.get(1), jsonArray.getClass());
log.info("------Element 2: {} Type: {}------", jsonArray.get(2), jsonArray.getClass());
}Result screenshot omitted.
2.4 List to Json String
@Test
public void listToJsonStr() {
List
list = new ArrayList<>();
Computer computerOne = new Computer();
computerOne.setCpu("r7-4800h");
computerOne.setGpu("RTX-3060");
computerOne.setSsd("512GB");
list.add(computerOne);
Computer computerTwo = new Computer();
computerTwo.setCpu("i5-12600k");
computerTwo.setGpu("RTX-3060Ti");
computerTwo.setSsd("512GB");
list.add(computerTwo);
String listJson = JSON.toJSONString(list);
System.out.println(listJson);
}Result screenshot omitted.
2.5 Map to Json String
@Test
public void mapToJsonStr() {
Map
map = new HashMap<>();
map.put("key1", "AAA");
map.put("key2", "bbb");
map.put("key3", "CCC");
String mapJson = JSON.toJSONString(map);
System.out.println("mapJson:" + mapJson);
}Result screenshot omitted.
3. JSON → Other Types
3.1 Json String to JavaBean
@Test
public void jsonStrToJavaBean() {
Computer computer = new Computer();
computer.setCpu("r7-4800h");
computer.setGpu("RTX-3060");
computer.setSsd("512GB");
computer.setMemory("32GB");
String jsonStr = JSON.toJSONString(computer);
System.out.println(jsonStr);
Computer result = JSONObject.parseObject(jsonStr, Computer.class);
System.out.println(result);
}Result screenshot omitted.
3.2 Json String to JsonObject
@Test
public void jsonStrToJsonObject() {
String jsonStr = "{ \"activityId\": \"871047729944117248\",\n" +
" \"activityType\": \"OA\",\n" +
" \"awardId\": \"886982449056579584\",\n" +
" \"awardName\": \"OA测试\" }";
JSONObject parse = JSONObject.parseObject(jsonStr);
System.out.println(parse.getString("activityId"));
}Result screenshot omitted.
3.3 Json String to List
@Test
public void jsonStrToList() {
String jsonStr = "[{ \"activityId\": \"871047729944117248\",\n" +
" \"activityType\": \"OA\",\n" +
" \"awardId\": \"886982449056579584\",\n" +
" \"awardName\": \"OA测试\" }]";
List
maps = JSONArray.parseArray(jsonStr, Map.class);
maps.forEach(System.out::println);
}Result screenshot omitted.
3.4 Json String to Map
@Test
public void jsonStrToMap() {
String jsonStr = "{\"AA\": 1,\"BB\":2,\"CC\":3}";
Map map = JSONObject.parseObject(jsonStr, Map.class);
map.forEach((k, v) -> System.out.println(k + "=" + v));
}Result screenshot omitted.
4. Json Interconversion
4.1 Json Array String to JsonArray
@Test
public void jsonStrToJsonArray() {
JSONArray jsonArray = new JSONArray();
Computer computer = new Computer();
computer.setCpu("r7-4800h");
computer.setGpu("RTX-3060");
computer.setSsd("512GB");
JSONObject jsonObject = new JSONObject();
jsonObject.put("AAA", 100);
jsonArray.add(computer);
jsonArray.add(jsonObject);
String str = JSONArray.toJSONString(jsonArray);
System.out.println(str);
String jsonArrStr = "[{\"cpu\" : \"r7-4800h\",\"gpu\" : \"RTX-3060\"},{\"cpu\" : \"i5-12600K\",\"gpu\" : \"RTX-3060Ti\"}]";
JSONArray result = JSONArray.parseArray(jsonArrStr);
result.forEach(o -> System.out.println(o.toString()));
}Result screenshot omitted.
4.2 JsonObject to Json String
@Test
public void jsonObjectToJsonStr() {
JSONObject jsonObject = new JSONObject();
Computer computer = new Computer();
computer.setCpu("r7-4800h");
computer.setGpu("RTX-3060");
computer.setSsd("512GB");
jsonObject.put("computer", computer);
String jsonStr = JSON.toJSONString(jsonObject);
System.out.println(jsonStr);
}Result screenshot omitted.
5. Conclusion
This article has shared a comprehensive overview of JSON format and practical conversion techniques used in daily development. If there are any errors or omissions, feedback is welcome, and readers are encouraged to discuss additional tips in the comments.
Java Captain
Focused on Java technologies: SSM, the Spring ecosystem, microservices, MySQL, MyCat, clustering, distributed systems, middleware, Linux, networking, multithreading; occasionally covers DevOps tools like Jenkins, Nexus, Docker, ELK; shares practical tech insights and is dedicated to full‑stack Java development.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.