我正在使用 JHipster(spring boot) 來生成我的專案。我想在 application.yml 中隱藏/顯示 JSON 中的欄位。舉個例子:
我有以下課程
@Entity
@Table(name = "port")
@Cache(usage = CacheConcurrencyStrategy.READ_WRITE)
public class Port implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "sequenceGenerator")
@SequenceGenerator(name = "sequenceGenerator")
@Column(name = "id")
private Long id;
@Column(name = "city")
private String city;
@Column(name = "description")
private String description;
//getters & setters
}
我的 GET 方法回傳如下回應:
{
"id": 1,
"city": "boston",
"description": "test test"
}
我希望能夠從 application.yml 中包含/排除某些欄位(因為我沒有 application.properties),否則會有類似的內容:
//application.yml
include: ['city']
exclude: ['description']
在此示例中,我的 json 應如下所示:
{
"id": 1,
"city": "boston",
}
例如,如果我有 40 個欄位并且我需要隱藏 10 并顯示 30 我只想將我想隱藏的 10 放在 application.yml 中的 exclude 中,而無需每次都更改代碼。我猜@jsonignore 隱藏欄位,但我不知道如何從 application.yml 做到這一點
很抱歉沒有很好地解釋。我希望這很清楚。
提前感謝您提供任何建議或解決方案來做類似的事情
uj5u.com熱心網友回復:
你可以嘗試在你的控制器中創建一個 hashmap 來管理你的 HTTP 回應。
Map<String, Object> map = new HashMap<>();
map.put("id", Port.getId());
map.put("city", Port.getCity());
return map;
uj5u.com熱心網友回復:
基本上,您不會Port在 REST 控制器中公開您的物體,而是使用一個簡單的類(例如)公開一個 DTO(資料傳輸物件),您可以從服務層中的物體中獲取它的價值PortMapper。PortDTO也可能是Map其他答案中所建議的。
然后,您的服務層可以使用一個配置物件(例如PortMapperConfiguration),該物件被賦值application.yml并用于有條件地從getterPortMapper呼叫PortDTOsetter 。Port
@ConfigurationProperties(prefix = "mapper", ignoreUnknownFields = false)
public class PortMapperConfiguration {
private List<String> include;
private List<String> exclude;
// getters/setters
}
@Service
public class PortMapper {
private PortMapperConfiguration configuration;
public PortMapper(PortMapperConfiguration configuration) {
this.configuration = configuration;
}
public PortDTO toDto(Port port) {
PortDTO dto = new PortDTO();
// Fill DTO based on configuration
return dto;
}
}
uj5u.com熱心網友回復:
Spring boot 默認使用 Jackson JSON 庫將您的類序列化為 Json。在該庫中,有一個注釋@JsonIgnore精確用于告訴 Json 引擎從序列化/反序列化中忽略特定屬性。因此,假設在您的物體中,Port您希望從顯示中排除房地產城市。您所要做的就是用注解對該屬性(或其getter 方法)進行@JsonIgnore注解:
@Column(name = "city")
@JsonIgnore
private String city;
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/439308.html
