在一次營(yíng)銷組件化的開發(fā)中恼蓬。依賴方小伙伴強(qiáng)烈要求我們提供工具包用來解析類似黑盒的大json串串涮阔。小伙伴們并不想理解黑盒內(nèi)容猴伶,但是想獲取他們需要的葉子節(jié)點(diǎn)的數(shù)值厢汹。
{
"data": {
"creator": "{\"id\":\"666666\",\"name\":\"大頭\",\"prefix\":\"dt666666\"}",
"name": "大頭大頭下雨不愁",
"dateRange": "{\"start\":\"2020-06-30 00:00:00\",\"end\":\"2020-06-30 23:59:59\"}",
"activityTemplate": "0",
"periodAndRule": "[{\"weekday\":\"2\",\"timeRange\":{\"start\":\"00:00:00\",\"end\":\"23:59:59\"},\"rule\":[{\"condition\":1200,\"discount\":100,\"shopSubsidy\":100,\"elemeSubsidy\":0}]}]",
"userDayOrderLimit": "{\"limit\":\"1\"}",
"userScope": "0"
},
"instanceId": 423014
}
問題來了螟深,怎么方便又快速拿到葉子節(jié)點(diǎn)的值呢?在我們營(yíng)銷組件的場(chǎng)景下data下面的值是可以枚舉的烫葬,而且枚舉可以表示很多營(yíng)銷模型的意義界弧。那么將這種json的轉(zhuǎn)化為有父枚舉類型嵌套結(jié)構(gòu),能準(zhǔn)確表達(dá)出json的對(duì)象關(guān)系搭综。
public enum MktField{
NAME("name",null,"活動(dòng)名稱"),
/**
* 創(chuàng)建者對(duì)象
*/
CREATOR("creator", null,"創(chuàng)建者"),
CREATOR_ID("id", CREATOR,"創(chuàng)建者ID"),
CREATOR_NAME("name", CREATOR, "創(chuàng)建者name"),
CREATOR_PREFIX("prefix", CREATOR, "前綴"),
CREATOR_TYPE("creatorType", null,"創(chuàng)建者類型"),
......
public String key;
public MktField parent;
public String title;
MktField(String key, MktField parent, String title) {
this.key = key;
this.parent = parent;
this.title = title;
}
......
}
剩下的就寫一個(gè)小工具來方便提取具體含義的值就好了垢箕。這種結(jié)構(gòu)對(duì)遞歸太友好,所以我直接用了遞歸兑巾。這樣根據(jù)枚舉值以及大json對(duì)象条获,就能方便的黑盒方式獲取葉子的值了。
private static Object getMktFieldValue(MktField field, JSONObject fieldMetaJson){
try {
JSONObject oj;
if (field.getParent() == null) {
return fieldMetaJson.get(field.getKey());
} else {
if (getMktFieldValue(field.getParent(), fieldMetaJson) instanceof String){
oj = JSON.parseObject((String) getMktFieldValue(field.getParent(), fieldMetaJson));
} else {
oj = (JSONObject) getMktFieldValue(field.getParent(), fieldMetaJson);
}
}
return oj.get(field.getKey());
}catch (Exception e){
return null;
}
}