fastjson是阿里的一款对Json处理的工具,使用前需要引入对应的jar包下载地址
package json;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import com.alibaba.fastjson.JSON;
public class FastJsonDemo {
//对象转Json
public static String ClassToJson() {
User user = new User();
user.setId(\"1\");
user.setName(\"王二麻子\");
String json = JSON.toJSONString(user);
return json;
}
//Json转对象
public static User JsonToClass() {
String classJson = ClassToJson();
User user = JSON.parse (classJson,User.class);
return user;
}
//List转Json
public static String ListToJson() {
List<User> userList = new ArrayList<>();
userList.add(new User(\"1\",\"王一麻子\"));
userList.add(new User(\"2\",\"王二麻子\"));
userList.add(new User(\"3\",\"王三麻子\"));
userList.add(new User(\"4\",\"王四麻子\"));
userList.add(new User(\"5\",\"王五麻子\"));
userList.add(new User(\"6\",\"王六麻子\"));
String json = JSON.toJSONString(userList);
return json;
}
//Json转List
public static List<User> JsonToList(){
String listJson = ListToJson();
List<User> userList = JSON.parseArray(listJson,User.class);
return userList;
}
//parse这个方法比较通用,但是无法精确泛型
public static List JsonToList2() {
String listJson = ListToJson();
List userList = (List)JSON.parse(listJson);
return userList;
}
//Map转Json
public static String MapToJson() {
Map<String,User> map = new HashMap<>();
map.put(\"大哥\", new User(\"1\",\"李狗蛋子\"));
map.put(\"二哥\", new User(\"2\",\"李猫蛋子\"));
map.put(\"三哥\", new User(\"3\",\"李竹鼠蛋子\"));
String json = JSON.toJSONString(map);
return json;
}
//Json转Map
public static Map JsonToMap() {
String mapJson = MapToJson();
Map map = (Map)JSON.parse (mapJson,Map.class);
return map;
}
//通用的方法,但是无法确定泛型
public static Map JsonToMap2() {
String mapJson = MapToJson();
//这2中写法都非常通用
//Map map = (Map)JSON.parse(mapJson);
Map map = JSON.parse (mapJson);
return map;
}
public static void main(String[] args) {
System.out.println(ClassToJson());//对象转Json
System.out.println(JsonToClass());//Json转对象
System.out.println(ListToJson());//List转Json
JsonToList().forEach(x->System.out.println(x));//Json转List集合
System.out.println(MapToJson());//Map转Json
JsonToMap().forEach((x,y) -> {System.out.println(x+\":\"+y);});//Json转Map
}
}
package json;
public class User {
private String id;
private String name;
public User() {
super();
}
public User(String id, String name) {
super();
this.id = id;
this.name = name;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@Override
public String toString() {
return \"User [id=\" + id + \", name=\" + name + \"]\";
}
}
继续阅读与本文标签相同的文章
下一篇 :
Theano退役,Bengio发出告别信
-
花旗投资现金流量预测公司Cashforce,拟新添增值服务
2026-05-18栏目: 教程
-
开发者必读 · 周报 | 003期
2026-05-18栏目: 教程
-
科技巨头正在合作解决自动驾驶标准!
2026-05-18栏目: 教程
-
人工智能帮助设计自行车并打破竞速纪录
2026-05-18栏目: 教程
-
分层存储超详细解读,为什么大数据时代它已不可或缺
2026-05-18栏目: 教程
