在接口開發中我們經常會遇到一個問題,打個比方,我們的實體類A中有兩個字段user和pwd但是接口中需要username和password這怎么辦呢,我想到了兩種方法:
1.新創建一個實體類B或者new一個map,將A中的字段一個一個取出來再放到B中或者放到map中
這種方法如果字段少的話還好,但若是字段多那就太麻煩了。
2.這種方法我來詳細說下:
首先新建一個實體類,我稱之為中間實體類,為了簡單我就不寫那么多字段了
package com.qcr.jituan.sys.service.contract.impl;
import com.fasterxml.jackson.annotation.JsonAlias;
import com.fasterxml.jackson.annotation.JsonProperty;
public class SealSaveFieldSync {
@JsonProperty("sid")
private String pkSeal;//主鍵
@JsonProperty("bcode")
private String vssubtypecode;
@JsonProperty("pname")
private String vssubtypename;
@JsonProperty("porg")
private String vssubordid;
@JsonProperty("vorgname")
private String vssubordname;
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
說明:數字1對應接口中的參數字段;數字2對應我們實體類中的字段
實體類寫好了接下來就是重點了,為了代碼的工整,我是直接提取出來一個方法
/**
* 實體類轉Map
* @param seal
* @return
*/
public static HashMap<String, String> entityToMap(SealVO seal) {
HashMap<String, String> map = new HashMap();
for (Field field : seal.getClass().getDeclaredFields()){
try {
boolean flag = field.isAccessible();
field.setAccessible(true);
Object o = field.get(seal);
if (o != null){
Field contField = SealSaveFieldSync.class.getDeclaredField(field.getName());
JsonProperty voField = contField.getAnnotation(JsonProperty.class);
String s = voField.value();
map.put(s, o.toString());
}
field.setAccessible(flag);
} catch (Exception e) {
e.printStackTrace();
}
}
return map;
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
代碼中的seal是我的實體類,通過這種方法我們得到的數據是這樣的:
通過這種方法可以簡單快速的將實體類中一個字段名稱,轉換成了另一個字段!!
感謝閱讀!!
---------------------