JSON工具类
fastjson
xml
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.76</version>
</dependency>
JSON字符串转对象
java实现
java
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.annotation.JSONField;
import lombok.Data;
import java.util.Date;
@Data
public class User {
private String id;
@JSONField(name = "user_name") // 指定JSON中的字段名与Java对象字段名不一致时的映射
private String userName;
@JSONField(format = "yyyy-MM-dd") // 指定日期格式化
private Date birthDate;
public static void main(String[] args) {
String jsonString = "{\"id\":\"123\", \"user_name\":\"张三\", \"birth_date\":\"1990-01-01\"}";
// 将JSON字符串转换为User对象
User user = JSON.parseObject(jsonString, User.class);
System.out.println(user.getId()); // 输出: 123
System.out.println(user.getUserName()); // 输出: 张三
System.out.println(user.getBirthDate()); // 输出: Mon Jan 01 00:00:00 CST 1990
}
}