我們在開發(fā)過程中經(jīng)常會遇到解析Json字符串的情況,這時候采用開源工具可以快速將json字符串映射為pojo對象。而在某些業(yè)務(wù)場景中,往往為了獲得json字符串中某個屬性的值而不得不定義一個pojo類,從而形成與json字符串的對應(yīng)。一旦json格式發(fā)生改變。pojo類也不得不作相應(yīng)修改。
這時候可以考慮將json與Map映射。只要知道具體的屬性名即可獲取屬性值。
假設(shè)有如下Json字符串
{
"id": 100,
"name": "scott",
"birthday": 1480785217693,
"org": {
"id": 1,
"name": "銷售部"
}
}
由于Json格式都是鍵值對形式存在,所以直接映射Map類型即可。這里采用Gson作為Json解析工具。
Gson gson = new GsonBuilder().create();
String json = "{\"id\":100,\"name\":\"scott\",\"birthday\":\"Dec 4, 2016 1:10:33 AM\",\"org\":{\"id\":1,\"name\":\"銷售部\"}}";
Map map = gson.fromJson(json, Map.class);
如何取值?傳統(tǒng)循環(huán)方式
這里用.作為屬性名之間的分隔符。
-
定義解析Map的方法
private <T> T getValueByMap(String path,Map<String, Object> map,Class<T> clazz,Object defaultVal){ String[] params = path.split("\\."); for(int i=0;i<params.length-1;i++){ map = (Map)map.get(params[i]); } Object result = null; result = map.get(params[params.length-1]); return result == null ? (T) defaultVal : (T) result; } -
調(diào)用上述方法
String name = getValueByMap("org.name",map,String.class,""); System.out.println(name); double birthday = getValueByMap("birthday",map,double.class,""); System.out.println(new Double(birthday).longValue());
Ognl方式,采用該方式需引入Ognl依賴
<dependency>
<groupId>ognl</groupId>
<artifactId>ognl</artifactId>
<version>3.1.12</version>
</dependency>
代碼實現(xiàn)
private <T> T getValueByMap(String path, Map<String, Object> map, Class<T> clazz, Object defaultVal) throws OgnlException {
OgnlContext context = new OgnlContext();
context.putAll(map);
Object value = Ognl.getValue(path, context);
return value == null ? (T) defaultVal : (T) value;
}
Json數(shù)組處理
假設(shè)json字符串如下:
{
"id": 1,
"name": "銷售部",
"empSet": [
{
"id": 2,
"name": "scott 2",
"birthday": 1480787444646
},
{
"id": 3,
"name": "scott 3",
"birthday": 1480787444646
},
{
"id": 4,
"name": "scott 4",
"birthday": 1480787444646
},
{
"id": 0,
"name": "scott 0",
"birthday": 1480787444646
},
{
"id": 1,
"name": "scott 1",
"birthday": 1480787444646
}
]
}
-
用List與Json字符串中的數(shù)組部門映射即可。
Gson gson = new GsonBuilder().create(); String json = "{\"id\":1,\"name\":\"銷售部\",\"empSet\":[{\"id\":2,\"name\":\"scott 2\",\"birthday\":1480787444646},{\"id\":3,\"name\":\"scott 3\",\"birthday\":1480787444646},{\"id\":4,\"name\":\"scott 4\",\"birthday\":1480787444646},{\"id\":0,\"name\":\"scott 0\",\"birthday\":1480787444646},{\"id\":1,\"name\":\"scott 1\",\"birthday\":1480787444646}]}"; Map map = gson.fromJson(json, Map.class); List emps = getValueByMap("empSet", map, List.class, ""); System.out.println(emps);