如何在Java中实现JSON格式转换?附具体转换示例
在Java里处理JSON格式转换,最常用的就是Jackson或者Gson这类成熟的序列化库。我先默认你想要的是按propertyId分组的目标格式(如果你的预期输出是其他结构,随时补充细节我再调整),下面给你两种主流库的实现方案:
使用Jackson实现转换
1. 引入依赖
如果用Maven,在pom.xml中添加Jackson的核心依赖:
<dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-databind</artifactId> <version>2.15.2</version> <!-- 建议使用最新稳定版 --> </dependency>
2. 定义实体类
先把输入的JSON条目映射成Java实体,方便后续操作:
import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import java.time.LocalDateTime; @JsonIgnoreProperties(ignoreUnknown = true) // 忽略JSON中未定义的字段,适配你输入里的"..." public class Reservation { private int propertyId; private int roomId; private LocalDateTime startDate; private LocalDateTime endDate; private int priority; private String message; private int id; private LocalDateTime dateModifiedUtc; // 生成getter和setter方法,或者用Lombok的@Data注解简化代码 }
3. 编写转换逻辑
解析输入JSON为实体列表,按propertyId分组后再转成目标JSON:
import com.fasterxml.jackson.core.type.TypeReference; import com.fasterxml.jackson.databind.ObjectMapper; import java.util.List; import java.util.Map; import java.util.stream.Collectors; public class JsonTransformer { public static void main(String[] args) throws Exception { // 你的输入JSON字符串 String inputJson = "[ { \"propertyId\":10081, \"roomId\":0, \"startDate\":\"2018-01-29T00:00:00\", \"endDate\":\"2018-01-30T00:00:00\", \"priority\":1, \"message\":\"Test it\", \"id\":158, \"dateModifiedUtc\":null }, { \"propertyId\":10081, \"roomId\":10021855, \"startDate\":\"2018-01-29T00:00:00\", \"endDate\":\"2018-01-30T00:00:00\", \"priority\":2, \"message\":\"Check how it works\", \"id\":159, \"dateModifiedUtc\":null } ]"; ObjectMapper objectMapper = new ObjectMapper(); objectMapper.findAndRegisterModules(); // 配置支持LocalDateTime类型 // 解析输入JSON为Reservation列表 List<Reservation> reservations = objectMapper.readValue( inputJson, new TypeReference<List<Reservation>>() {} ); // 按propertyId分组,key为propertyId的字符串形式 Map<String, List<Reservation>> groupedReservations = reservations.stream() .collect(Collectors.groupingBy(res -> String.valueOf(res.getPropertyId()))); // 转换为格式化后的目标JSON String outputJson = objectMapper.writerWithDefaultPrettyPrinter() .writeValueAsString(groupedReservations); System.out.println(outputJson); } }
使用Gson实现转换
如果你更习惯用Gson,也可以按下面的步骤来:
1. 引入依赖
Maven依赖配置:
<dependency> <groupId>com.google.code.gson</groupId> <artifactId>gson</artifactId> <version>2.10.1</version> <!-- 最新稳定版 --> </dependency>
2. 定义实体类
Gson对实体类的要求更宽松,不需要额外注解(除非有特殊字段映射需求):
import java.time.LocalDateTime; public class Reservation { private int propertyId; private int roomId; private LocalDateTime startDate; private LocalDateTime endDate; private int priority; private String message; private int id; private LocalDateTime dateModifiedUtc; // getter和setter方法,或用Lombok简化 }
3. 转换逻辑
import com.google.gson.Gson; import com.google.gson.GsonBuilder; import com.google.gson.reflect.TypeToken; import java.lang.reflect.Type; import java.util.List; import java.util.Map; import java.util.stream.Collectors; public class GsonTransformer { public static void main(String[] args) { String inputJson = "[ { \"propertyId\":10081, \"roomId\":0, \"startDate\":\"2018-01-29T00:00:00\", \"endDate\":\"2018-01-30T00:00:00\", \"priority\":1, \"message\":\"Test it\", \"id\":158, \"dateModifiedUtc\":null }, { \"propertyId\":10081, \"roomId\":10021855, \"startDate\":\"2018-01-29T00:00:00\", \"endDate\":\"2018-01-30T00:00:00\", \"priority\":2, \"message\":\"Check how it works\", \"id\":159, \"dateModifiedUtc\":null } ]"; Gson gson = new GsonBuilder().setPrettyPrinting().create(); // 开启格式化输出 Type reservationListType = new TypeToken<List<Reservation>>() {}.getType(); // 解析输入JSON List<Reservation> reservations = gson.fromJson(inputJson, reservationListType); // 按propertyId分组 Map<String, List<Reservation>> groupedMap = reservations.stream() .collect(Collectors.groupingBy(res -> String.valueOf(res.getPropertyId()))); // 生成目标JSON String outputJson = gson.toJson(groupedMap); System.out.println(outputJson); } }
额外说明
如果你的目标格式不是按propertyId分组,而是需要调整字段名、提取特定字段或者其他结构,只需要修改分组后的处理逻辑,或者通过注解(比如Jackson的@JsonProperty、Gson的@SerializedName)来调整字段映射关系即可。
内容的提问来源于stack exchange,提问作者spacecraft
相关产品推荐
相关产品推荐

