若是簡單對象,那麼轉換的方式比較多,這裏指的複雜對象,是指對象裏面存在cycle引用,好比:json
/**
* @author ding
*
*/
@Entity
@Table(name = "service")
public class ServicePO implements Serializable{api
private static final long serialVersionUID = -6546556665143282079L;
@Id
@Column(name="service_pk")
@GeneratedValue(generator = "mcid")
@GenericGenerator(name="mcid",strategy="uuid2")
private String pk;
app
//包含的API
@JsonManagedReference(value="service-api")
@OneToMany(cascade={CascadeType.PERSIST,CascadeType.MERGE,CascadeType.REFRESH,CascadeType.REMOVE}, mappedBy = "servicePO", orphanRemoval = true)
private List<ApiPO> apiPOs;ide
......ui
//此處略去其餘屬性xml
}對象
/**
* @author ding
*/
@Entity
@Table(name = "link_api_info")
public class ApiPO implements Serializable{utf-8
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;
......ci
//此處略去其餘屬性get
}
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) { } }