FastJson Convert Java objects to / from JSON

摘要: FastJson provides easily APIs to convert Java objects to / from JSON

FastJson provides easily APIs to convert Java objects to / from JSON

  • JSON.toJSONString – Java objects to JSON
  • JSON.parseObject – JSON to Java objects
  • JSON.parseArray – JSON array to List of Java objects
Note
You may have interest to read this How to parse JSON with Jackson

Overall, the FastJson is really simple and easy to convert JSON to / from objects, however, it lack of direct File support, especially the JSON.parseArray method, it needs some extra efforts to read from a JSON file. Hope the future APIs like parseObject and parseArray are able to support for sources like File or URL directly.

P.S Tested with FastJson 1.2.57

pom.xml
	<dependency>
		<groupId>com.alibaba</groupId>
		<artifactId>fastjson</artifactId>
		<version>1.2.57</version>
	</dependency>

1. POJO

A simple POJO, for JSON conversion.

Staff.java
package com.mkyong;
import java.math.BigDecimal;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.Map;
public class Staff {
    private String name;
    private int age;
    private String[] position;
    private List<String> skills;
    private Map<String, BigDecimal> salary;
    //getters, setters, toString, constructor

2. Java objects to JSON

FastJsonExample1.java
package com.mkyong;
import com.alibaba.fastjson.JSON;
import java.io.IOException;
import java.math.BigDecimal;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.*;
public class FastJsonExample1 {
    public static void main(String[] args) {
        Staff staff = createStaff();
        // Java objects to JSON
        String json = JSON.toJSONString(staff);
        System.out.println(json);
        // Java objects to JSON, pretty-print
        String json2 = JSON.toJSONString(staff, true);
        System.out.println(json2);
        // Java objects to JSON, with formatted date
        String json3 = JSON.toJSONStringWithDateFormat(staff, "dd/MM/yyyy HH:mm:ss");
        System.out.println(json3);
        // List of Java objects to JSON Array
        List<Staff> list = Arrays.asList(createStaff(), createStaff());
        String json4 = JSON.toJSONStringWithDateFormat(list, "dd/MM/yyyy HH:mm:ss");
        System.out.println(json4);
        try {
            // can't find fastjson api to write files, np, just use the standard java.nio Files.write
            Files.write(Paths.get("c:\\projects\\staff.json"), json4.getBytes());
        } catch (IOException e) {
            e.printStackTrace();
    private static Staff createStaff() {
        Staff staff = new Staff();
        staff.setName("mkyong");
        staff.setAge(38);
        staff.setPosition(new String[]{"Founder", "CTO", "Writer"});
        Map<String, BigDecimal> salary = new HashMap() {{
            put("2010", new BigDecimal(10000));
            put("2012", new BigDecimal(12000));
            put("2018", new BigDecimal(14000));
        }};
        staff.setSalary(salary);
        staff.setSkills(Arrays.asList("java", "python", "node", "kotlin"));
        staff.setJoinDate(new Date());
        return staff;

Output

// json
{"age":38,"joinDate":1556870430099,"name":"mkyong","position":["Founder","CTO","Writer"],
"salary":{"2018":14000,"2012":12000,"2010":10000},"skills":["java","python","node","kotlin"]}
// json2
	"age":38,
	"joinDate":1556870430099,
	"name":"mkyong",
	"position":["Founder","CTO","Writer"],
	"salary":{
		"2018":14000,
		"2012":12000,
		"2010":10000
	},
	"skills":[
		"java",
		"python",
		"node",
		"kotlin"
// json3 - format date
{"age":38,"joinDate":"03/05/2019 16:00:30","name":"mkyong","position":["Founder","CTO","Writer"],
"salary":{"2018":14000,"2012":12000,"2010":10000},"skills":["java","python","node","kotlin"]}
// json4 - JSON Array
		"age":38,
		"joinDate":1556870630615,
		"name":"mkyong",
		"position":["Founder","CTO","Writer"],
		"salary":{
			"2018":14000,
			"2012":12000,
			"2010":10000
		},
		"skills":[
			"java",
			"python",
			"node",
			"kotlin"
	},
		"age":38,
		"joinDate":1556870630615,
		"name":"mkyong",
		"position":["Founder","CTO","Writer"],
		"salary":{
			"2018":14000,
			"2012":12000,
			"2010":10000
		},
		"skills":[
			"java",
			"python",
			"node",
			"kotlin"

3. JSON to Java objects

FastJsonExample2.java
package com.mkyong;
import com.alibaba.fastjson.JSON;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;
public class FastJsonExample2 {
    public static void main(String[] args) {
        // JSON string to Java object
        String jsonString = "{\"name\":38,\"name\":\"mkyong\"}";
        Staff staff = JSON.parseObject(jsonString, Staff.class);
        System.out.println(staff);
        // JSON array to Java object
        String jsonArray = "[{\"name\":38,\"name\":\"mkyong\"}, {\"name\":39,\"name\":\"mkyong2\"}]";
        List<Staff> staff1 = JSON.parseArray(jsonArray, Staff.class);
        System.out.println(staff1);
        // JSON array in File to Java object
        // staff.json contain JSON array
        try (Stream<String> lines = Files.lines(Paths.get("c:\\projects\\staff.json"))) {
            String content = lines.collect(Collectors.joining());
			// Hope parseArray() will support File or Reader in future.
            List<Staff> list = JSON.parseArray(content, Staff.class);
            System.out.println(list);
        } catch (IOException e) {
            e.printStackTrace();

上一篇: Java How to save a String to a File
下一篇: Java password generator example
 评论 ( What Do You Think )
名称
邮箱
网址
评论
验证
   
 

 


  • 微信公众号

  • 我的微信

站点声明:

1、一号门博客CMS,由Python, MySQL, Nginx, Wsgi 强力驱动

2、部分文章或者资源来源于互联网, 有时候很难判断是否侵权, 若有侵权, 请联系邮箱:summer@yihaomen.com, 同时欢迎大家注册用户,主动发布无版权争议的 文章/资源.

3、鄂ICP备14001754号-3, 鄂公网安备 42280202422812号