常用的JSON的方法
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 +
'}';
}
}

浙公网安备 33010602011771号