#fastjson 的简单用法
最近项目中接触到 fastjson 随手记录下关于 fastjson 的使用
[TOC]
导入依赖
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.60</version>
</dependency>
JSON 字符串 -> 类实例
简单 JSON 字符串-> Java 对象
app.java
public class App
{
public static void main( String[] args )
{
String msg = "{\"name\":\"java\",\"sex\":\"unknown\",\"age\":24}";
User user = JSON.parseObject(msg, User.class);
System.out.println(user);
}
}
User.java
public class User {
@JSONField(name = "name")
private String name;
@JSONField(name = "sex")
private String sex;
@JSONField(name = "age")
private int age;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getSex() {
return sex;
}
public void setSex(String sex) {
this.sex = sex;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
@Override
public String toString() {
return "User{" +
"name='" + name + '\'' +
", sex='" + sex + '\'' +
", age=" + age +
'}';
}
}
简单 JSON 字符串 -> JSON 对象
String msg = "{\"name\":\"java\",\"sex\":\"unknown\",\"age\":24}";
JSONObject jsonObject = JSON.parseObject(msg);
System.out.println(jsonObject);
稍复杂 JSON 字符串 -> Json 对象
String msg = "{\"name\":\"java\",\"sex\":\"unknown\",\"age\":24,\"pets\":[{\"nick_name\":\"coco\",\"type\":\"cat\"},{\"nick_name\":\"kimi\",\"type\":\"dog\"}]}";
JSONObject jsonObject = JSON.parseObject(msg);
稍复杂 JSON 字符串 -> Java 对象
public static void main( String[] args )
{
String msg = "{\"name\":\"java\",\"sex\":\"unknown\",\"age\":24,\"pets\":[{\"nick_name\":\"coco\",\"type\":\"cat\"},{\"nick_name\":\"kimi\",\"type\":\"dog\"}]}";
User user = JSON.parseObject(msg, new TypeReference<User<Pet>>(){});
System.out.println(user);
}
User.java
public class User<T> {
@JSONField(name = "name")
private String name;
@JSONField(name = "sex")
private String sex;
@JSONField(name = "age")
private int age;
@JSONField(name = "pets")
private T[] pets;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getSex() {
return sex;
}
public void setSex(String sex) {
this.sex = sex;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public T[] getPets() {
return pets;
}
public void setPets(T[] pets) {
this.pets = pets;
}
}
Pet.java
public class Pet {
@JSONField(name = "nick_name")
private String nickName;
@JSONField(name = "type")
private String type;
public String getNickName() {
return nickName;
}
public void setNickName(String nickName) {
this.nickName = nickName;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
}
欢迎来到这里!
我们正在构建一个小众社区,大家在这里相互信任,以平等 • 自由 • 奔放的价值观进行分享交流。最终,希望大家能够找到与自己志同道合的伙伴,共同成长。
注册 关于