常用的JSON的方法
阿新 • • 發佈:2022-03-20
1.JSON物件與JAVA物件互轉
核心程式碼
JSON.parseObject(String, XXX.class);
import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.JSONObject; import java.util.HashMap; import java.util.Map; public class JsonPractice { public static void main(String[] args) { Map<String,Object> map = new HashMap<>(); Object object = null; map.put("name","王五"); map.put("age",12); map.put("weight",120); map.put("height",160); JSONObject jsonObject = new JSONObject(map); Student student = JSON.parseObject(String.valueOf(jsonObject), Student.class); System.out.println(student); } }
附:其他程式碼
public class Student { private String name; private int age; private int weight; private int height; public String getName() { return name; } public void setName(String name) { this.name = name; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } public int getWeight() { return weight; } public void setWeight(int weight) { this.weight = weight; } public int getHeight() { return height; } public void setHeight(int height) { this.height = height; } public Student(String name, int age, int weight, int height) { this.name = name; this.age = age; this.weight = weight; this.height = height; } public Student() { } @Override public String toString() { return "Student{" + "name='" + name + '\'' + ", age=" + age + ", weight=" + weight + ", height=" + height + '}'; } }