如果简单对象,那么转换的方式比较多,这里指的复杂对象,是指对象里面存在cycle引用,比如:
/**
* @author ding
*
*/
@Entity
@Table(name = "service")
public class ServicePO implements Serializable{
private static final long serialVersionUID = -6546556665143282079L;
@Id
@Column(name="service_pk")
@GeneratedValue(generator = "mcid")
@GenericGenerator(name="mcid",strategy="uuid2")
private String pk;
//包含的API
@JsonManagedReference(value="service-api")
@OneToMany(cascade={CascadeType.PERSIST,CascadeType.MERGE,CascadeType.REFRESH,CascadeType.REMOVE}, mappedBy = "servicePO", orphanRemoval = true)
private List<ApiPO> apiPOs;
......
//此处略去其他属性
}
/**
* @author ding
*/
@Entity
@Table(name = "link_api_info")
public class ApiPO implements Serializable{
private static final long serialVersionUID = 7083439085753069767L;
@Id
@Column(name="api_pk")
@GeneratedValue(generator = "mcid")
@GenericGenerator(name="mcid",strategy="uuid2")
private String pk;
//服务
@ManyToOne(cascade = CascadeType.REFRESH)
@JsonBackReference(value="service-api")
@JoinColumn(name = "service_pk")
private ServicePO servicePO;
......
//此处略去其他属性
}
ServicePO 一对多ApiPO ,两个对象互相引用,虽然有json注解,但是一般的手动json转换不管用,下面就是解决方案~~
首先引入依赖:
<!-- https://mvnrepository.com/artifact/com.fasterxml.jackson.jaxrs/jackson-jaxrs-json-provider -->
<dependency>
<groupId>com.fasterxml.jackson.jaxrs</groupId>
<artifactId>jackson-jaxrs-json-provider</artifactId>
<version>2.8.0</version>
</dependency>
object转换为json:
JsonGenerator jsonGenerator = null;
ObjectMapper objectMapper = null;
String dd1 = "";
try (ByteArrayOutputStream byt = new ByteArrayOutputStream();){
objectMapper = new ObjectMapper();
jsonGenerator = objectMapper.getJsonFactory().createJsonGenerator(byt, JsonEncoding.UTF8);
jsonGenerator.useDefaultPrettyPrinter();
objectMapper.writeValue(jsonGenerator, servicePO);
byt.flush();
dd1 = new String(byt.toByteArray(), "utf-8");
} catch (IOException e) {
logger.info("servicePO对象转json失败:"+e.getMessage());
}
JSONObject dd = JSONObject.fromObject(dd1);
jsonToObject:
String service = serPoJson;
if(service != null && !"".equals(service)){
try {
ObjectMapper objectMapper = new ObjectMapper();
servicePO = objectMapper.readValue(service, ServicePO.class);
} catch (IOException e) {
}
}