您的位置:首页 > Web前端 > JavaScript

FastJson入门学习(4)

2020-08-06 11:26 435 查看

FastJson学习

初学者,多多指正

Person实体类
public class Person {

@JSONField(name = "id1",ordinal = 1)
private int id;

@JSONField(name = "yourName1",ordinal = 2)
private String yourName;

@JSONField(name = "birthday1",format = "yyyy-MM-dd",ordinal = 3)
private Date birthday;

public Person() {
}

public Person(int id, String yourName, Date birthday) {
this.id = id;
this.yourName = yourName;
this.birthday = birthday;
}

public int getId() {
return id;
}

public void setId(int id) {
this.id = id;
}

public String getYourName() {
return yourName;
}

public void setYourName(String yourName) {
this.yourName = yourName;
}

public Date getBirthday() {
return birthday;
}

public void setBirthday(Date birthday) {
this.birthday = birthday;
}

@Override
public String toString() {
return "Person{" +
"id=" + id +
", yourName='" + yourName + '\'' +
", birthday=" + birthday +
'}';
}
}
测试
public class JsonTest3 {

public static void main(String[] args) {
Person person1 = new Person(12,"xiaoxiao",new Date());

//java对象转json字符串
String s = JSON.toJSONString(person1);
System.out.println(s);

//JSONObject 继承JSON, 也就是说JSON有的功能一般JSONObject都有
//JSONObject 实现了Map接口,所以JSONObject实现了Map中所有的抽象方法
//json字符串转json对象
JSONObject jsonObject = JSON.parseObject(s);
System.out.println(jsonObject);
//根据json特性,根据key值获取对应的value值
System.out.println(jsonObject.get("id1"));
System.out.println(jsonObject.get("yourName1"));
System.out.println(jsonObject.get("birthday1"));

//        Object parse = JSON.parse(s);
//        System.out.println(parse);
}
}
结果展示
D:\JDK_IDEA\jdk\bin\java.exe ...
{"id1":12,"yourName1":"xiaoxiao","birthday1":"2020-08-06"}
{"yourName1":"xiaoxiao","id1":12,"birthday1":"2020-08-06"}
12
xiaoxiao
2020-08-06
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: