import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.JSONObject; public class FastjsonTest { public static void main(String[] args) { String jsonstr="{"id":"1001","name":"zs","age":18,"sex":"男","clazz":"一班"}"; //json->对象 // 通过反射进行转换 转换成指定对象 Student student = JSON.parseObject(jsonstr, Student.class); // System.out.println(student.toString()); //json->对象 // 通过反射进行转换 转换成默认JSONObject对象 不需要创新的对象 // //kv对象 hashmap // JSonObject jsonObject = JSON.parseObject(jsonstr); // Object id = jsonObject.get("id"); // System.out.println(id); String o = JSON.toJSONString(student); System.out.println(o); } }
import com.google.gson.Gson; import java.util.HashMap; // "k":"v",k:18,k:v // "id":1001,"name":"zs","age":18,"sex":"男","班级":"一班" public class GsonTest { public static void main(String[] args) { String jsonstr="{"id":"1001","name":"zs","age":18,"sex":"男","clazz":"一班"}"; System.out.println(jsonstr); Gson gson = new Gson(); //json转化成对象 Student student = gson.fromJson(jsonstr, Student.class); System.out.println(student.toString()); System.out.println(student.getClazz()); HashMapstringStringHashMap = new HashMap (); HashMap hashMap = gson.fromJson(jsonstr, stringStringHashMap.getClass()); System.out.println(hashMap); //对象转化成json //不是{k:v,k:v...} System.out.println("------------------"); // int[] strs={1,2,3,4,5,6,7,8,9}; // String s = gson.toJson(strs); // System.out.println(s); } }
package mysql; public class Student { private String id; private String name; private int age; private String gender; private String clazz; 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; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } public String getClazz() { return clazz; } public void setClazz(String clazz) { this.clazz = clazz; } public Student() { } @Override public String toString() { return "Student{" + "id='" + id + ''' + ", name='" + name + ''' + ", age=" + age + ", gender='" + gender + ''' + ", clazz='" + clazz + ''' + '}'; } public Student(String id, String name, int age, String gender, String clazz) { this.id = id; this.name = name; this.age = age; this.gender = gender; this.clazz = clazz; } public String getGender() { return gender; } public void setGender(String gender) { this.gender = gender; } }
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)