利用jackson-databind,復雜對象對象和json數據互轉


如果簡單對象,那么轉換的方式比較多,這里指的復雜對象,是指對象里面存在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) {
}
}


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM