生成JSON資料--fastjson(阿里)方法

Java仗劍走天涯發表於2017-05-05

fastjson(阿里)方法生成JSON資料:

與Gson類似,建立相應類,再使用JSON.toJSONString()新增物件

要求:生成如下JSON資料

1.{“age”:3,”name”:”zhangsan”,”sex”:true,”weight”:180}


程式碼:

package com.qf.demo7;

import com.alibaba.fastjson.JSON;
/**
 * Gson   toJson
 * FastJson   toJsonString
 * @author Administrator
 *
 */
public class Test {

    public static void main(String[] args) {
        Person1 person = new Person1("zhangsan",true,3,180);
        String json = JSON.toJSONString(person);
        System.out.println(json);
    }
}

class Person1{
    private String name;
    private boolean sex;
    private int age;
    private int weight;
    public Person1(String name,boolean sex, int age,int weight) {
        super();
        this.name = name;
        this.sex = sex;
        this.age = age;
        this.weight = weight;
    }
    public Person1() {
        super();
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public int getAge() {
        return age;
    }
    public void setAge(int age) {
        this.age = age;
    }

    public int getWeight() {
        return weight;
    }
    public void setWeight(int weight) {
        this.weight = weight;
    }
    public boolean isSex() {
        return sex;
    }
    public void setSex(boolean sex) {
        this.sex = sex;
    }
    @Override
    public String toString() {
        return "Person [name=" + name + "sex = "+sex+", age=" + age + "]";
    }

}

相關文章