使用Spring MVC 在JSON 回應中動態忽略來自Java 物件的欄位
在Spring MVC 應用程式中,我們經常遇到需要選擇性地排除某些特定欄位的情況。欄位不包含在 JSON 回應中。這通常是維護資料隱私和遵守安全法規所必需的。為了實現這一點,我們有多種選擇。
使用 @JsonIgnoreProperties
最簡單的解決方案是使用 @JsonIgnoreProperties 註解 POJO 並指定您想要的欄位名稱排除。例如:
<code class="java">@Entity @Table(name = "user") @JsonIgnoreProperties({ "encryptedPwd", "createdBy", "updatedBy" }) public class User implements java.io.Serializable { // Your getters and setters here... }</code>
這將指示 Spring MVC 在將物件序列化為 JSON 時忽略 @JsonIgnoreProperties 註解中指定的欄位。
將@JsonIgnore 與Jackson 註解結合使用
如果您希望對排除的欄位進行更精細的控制,您可以使用jackson-core 庫中的Jackson 註釋。例如:
<code class="java">import com.fasterxml.jackson.annotation.JsonIgnore; @JsonIgnore public String getEncryptedPwd() { return encryptedPwd; }</code>
在 getter 方法之前加入 @JsonIgnore 將阻止該欄位包含在 JSON 回應中。
使用自訂 JSON 序列化器
或者,您可以建立自訂 JSON 序列化器來定義根據您的要求動態排除欄位的邏輯。以下是使用Jackson 的範例:
<code class="java">import com.fasterxml.jackson.core.JsonGenerator; import com.fasterxml.jackson.databind.JsonSerializer; import com.fasterxml.jackson.databind.SerializerProvider; import java.io.IOException; public class IgnoreFieldsSerializer extends JsonSerializer<user> { private List<string> ignoredFields; // Constructor to set the list of ignored fields @Override public void serialize(User user, JsonGenerator jsonGenerator, SerializerProvider serializerProvider) throws IOException { jsonGenerator.writeStartObject(); for (Field field : user.getClass().getDeclaredFields()) { // Check if the field is in the ignored list if (!ignoredFields.contains(field.getName())) { jsonGenerator.writeFieldName(field.getName()); jsonGenerator.writeObject(field.get(user)); } } jsonGenerator.writeEndObject(); } }</string></user></code>
然後您可以在REST 控制器中使用自訂序列化器:
<code class="java">@RestController @RequestMapping("/user") public class UserController { @Autowired private UserService userService; @GetMapping("/{userId}") public ResponseEntity<user> getUser(@PathVariable Integer userId) { User user = userService.get(userId); ObjectMapper mapper = new ObjectMapper(); mapper.registerModule(new SimpleModule().addSerializer(User.class, new IgnoreFieldsSerializer(ignoredFields))); return ResponseEntity.ok(mapper.writeValueAsString(user)); } }</user></code>
透過ignoreFields參數提供要忽略的欄位清單,您可以動態控制JSON 回應中排除的欄位。
以上是如何在 Spring MVC 應用程式中動態排除 Java 物件 JSON 回應中的欄位?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

Javaremainsagoodlanguageduetoitscontinuousevolutionandrobustecosystem.1)Lambdaexpressionsenhancecodereadabilityandenablefunctionalprogramming.2)Streamsallowforefficientdataprocessing,particularlywithlargedatasets.3)ThemodularsystemintroducedinJava9im

Javaisgreatduetoitsplatformindependence,robustOOPsupport,extensivelibraries,andstrongcommunity.1)PlatformindependenceviaJVMallowscodetorunonvariousplatforms.2)OOPfeatureslikeencapsulation,inheritance,andpolymorphismenablemodularandscalablecode.3)Rich

Java的五大特色是多態性、Lambda表達式、StreamsAPI、泛型和異常處理。 1.多態性讓不同類的對象可以作為共同基類的對象使用。 2.Lambda表達式使代碼更簡潔,特別適合處理集合和流。 3.StreamsAPI高效處理大數據集,支持聲明式操作。 4.泛型提供類型安全和重用性,編譯時捕獲類型錯誤。 5.異常處理幫助優雅處理錯誤,編寫可靠軟件。

java'stopfeatureSnificallyenhanceItsperformanCandScalability.1)對象 - 方向clincipleslike-polymormormormormormormormormormormormorableableflexibleandscalablecode.2)garbageCollectionAutectionAutoctionAutoctionAutoctionAutoctionAutoctionAutoMenateMememorymanateMmanateMmanateMmanagementButCancausElatemention.3)

JVM的核心組件包括ClassLoader、RuntimeDataArea和ExecutionEngine。 1)ClassLoader負責加載、鏈接和初始化類和接口。 2)RuntimeDataArea包含MethodArea、Heap、Stack、PCRegister和NativeMethodStacks。 3)ExecutionEngine由Interpreter、JITCompiler和GarbageCollector組成,負責bytecode的執行和優化。

Java'ssafetyandsecurityarebolsteredby:1)strongtyping,whichpreventstype-relatederrors;2)automaticmemorymanagementviagarbagecollection,reducingmemory-relatedvulnerabilities;3)sandboxing,isolatingcodefromthesystem;and4)robustexceptionhandling,ensuringgr

Javaoffersseveralkeyfeaturesthatenhancecodingskills:1)對象 - 方向 - 方向上的allowslowsmodelowsmodelingreal-worldentities

thejvmisacrucialcomponentthatrunsjavacodebytranslatingitolachine特定結構,影響性能,安全性和便攜性。 1)theclassloaderloader,links andinitializesClasses.2)theexecutionEngineExecutionEngineExecutionEngineExecuteNexeCuteByteCuteByteCuteByTecuteByteCuteByteCuteBytecuteBytecuteByteCoDeinintolachineinstructionsions.3)Memo.3)Memo


熱AI工具

Undresser.AI Undress
人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover
用於從照片中去除衣服的線上人工智慧工具。

Undress AI Tool
免費脫衣圖片

Clothoff.io
AI脫衣器

Video Face Swap
使用我們完全免費的人工智慧換臉工具,輕鬆在任何影片中換臉!

熱門文章

熱工具

記事本++7.3.1
好用且免費的程式碼編輯器

SublimeText3漢化版
中文版,非常好用

禪工作室 13.0.1
強大的PHP整合開發環境

SublimeText3 Linux新版
SublimeText3 Linux最新版

WebStorm Mac版
好用的JavaScript開發工具