在Java中,对象转换为JSON字符串以及JSON字符串转换为Java对象是非常常见的操作,通常我们会使用一些库来帮助我们完成这一过程。最常用的两个库是Gson和Jackson。
pom.xml
中添加如下依赖: 1 2 3 4 5 | < dependency > < groupId >com.google.code.gson</ groupId > < artifactId >gson</ artifactId > < version >2.8.9</ version > </ dependency > |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 | import com.google.gson.Gson; public class Main { static class Person { String name; int age; // 构造方法、getters、setters省略 } public static void main(String[] args) { Person person = new Person(); person.setName( "Tom" ); person.setAge( 30 ); Gson gson = new Gson(); String json = gson.toJson(person); System.out.println(json); // 输出:{"name":"Tom","age":30} } } |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 | import com.google.gson.Gson; import com.google.gson.reflect.TypeToken; import java.lang.reflect.Type; import java.util.Map; public class GsonToJsonExample { // 假设KnowPointStatical是一个具有相应getter和setter方法的Java Bean static class KnowPointStatical { String pointName; int totalQuestions; // 其他属性及getter和setter省略 } public static void main(String[] args) { String jsonString = "{" + "\"Math\": {\"totalQuestions\": 50}," + "\"English\": {\"totalQuestions\": 45}," + "\"Science\": {\"totalQuestions\": 60}" + "}" ; Gson gson = new Gson(); // 定义类型Token来指示目标类型 Type type = new TypeToken<Map<String, KnowPointStatical>>(){}.getType(); try { // 直接将JSON字符串转换为指定类型的Map Map<String, KnowPointStatical> map = gson.fromJson(jsonString, type); // 打印Map内容 for (Map.Entry<String, KnowPointStatical> entry : map.entrySet()) { System.out.println( "Subject: " + entry.getKey() + ", Total Questions: " + entry.getValue().getTotalQuestions()); } } catch (Exception e) { e.printStackTrace(); } } } |