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
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
package mobvista.prd.datasource.udf;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import mobvista.prd.datasource.util.GsonUtil;
import org.apache.commons.lang.StringUtils;
import org.apache.hadoop.hive.ql.exec.UDF;
import org.apache.hadoop.io.Text;
import java.util.ArrayList;
import java.util.List;
public class ParseJson extends UDF {
public List<Text> evaluate(String jsonArrayStr, String key) {
if (StringUtils.isBlank(jsonArrayStr) || StringUtils.isBlank(jsonArrayStr)) {
return null;
}
List<Text> textList = new ArrayList<Text>();
if (!jsonArrayStr.trim().startsWith("[")) {
textList.add(new Text(jsonArrayStr));
} else {
JsonArray array = GsonUtil.String2JsonArray(jsonArrayStr);
JsonObject json = null;
for (JsonElement element : array) {
json = element.getAsJsonObject();
JsonElement e = json.get(key);
if (e != null && !e.isJsonNull()) {
textList.add(new Text(e.getAsString()));
} else {
textList.add(new Text(""));
}
}
}
return textList;
}
public List<Text> evaluate(String jsonArrayStr, String key, String regex) {
if (StringUtils.isBlank(jsonArrayStr) || StringUtils.isBlank(jsonArrayStr)) {
return null;
}
List<Text> textList = new ArrayList<Text>();
if (!jsonArrayStr.trim().startsWith("[")) {
textList.add(new Text(jsonArrayStr));
} else {
JsonArray array = GsonUtil.String2JsonArray(jsonArrayStr);
JsonObject json = null;
for (JsonElement element : array) {
json = element.getAsJsonObject();
JsonElement e = json.get(key);
if (e != null && !e.isJsonNull() && e.getAsString().matches(regex)) {
textList.add(new Text(e.getAsString()));
}
}
}
return textList;
}
}