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
}
}
取属性
java
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.JSONPath;
@Test
public void test() throws Exception {
String json = "{\"name\":\"xx\"}";
String json2 = "[{\"name\":\"xx\"},{\"name\":\"xx2\"}]";
String json3 = "{\"code\":200,\"data\":[{\"id\":1,\"name\":\"admin\",\"age\":28},{\"id\":2,\"name\":\"test\",\"age\":30}]}";
Object read = JSONPath.read(json, "$.name");
Object read2 = JSONPath.read(json2, "$.name");
Object read3 = JSONPath.read(json3, "$.data[*].name");
System.out.println(read);
System.out.println(read2);
System.out.println(read3);
}
xx
["xx","xx2"]
["admin","test"]