Skip to content

Commit adc1f54

Browse files
committed
支持配置JSON,并自动转成相应类型
1 parent 2ac5c82 commit adc1f54

File tree

2 files changed

+42
-3
lines changed

2 files changed

+42
-3
lines changed

disconf-client/src/main/java/com/baidu/disconf/client/support/utils/ClassUtils.java

+16-3
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,8 @@
55
import java.util.HashSet;
66
import java.util.Set;
77

8+
import com.google.gson.Gson;
9+
810
/**
911
* 类工具
1012
*
@@ -155,9 +157,20 @@ public static Object getValeByType(Class<?> type, Object value)
155157

156158
return Double.valueOf(dataValue);
157159

158-
} else {
159-
160-
return value;
160+
} else if (typeName.equals("string")
161+
|| typeName.equals("java.lang.string")) {
162+
163+
return dataValue;
164+
}
165+
else {
166+
try {
167+
// 其他类型尝试JSON解析
168+
Gson gson = new Gson();
169+
return gson.fromJson(value.toString(), type);
170+
} catch (Exception ex) {
171+
ex.printStackTrace();
172+
}
173+
return value;
161174
}
162175
}
163176

Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
package com.baidu.disconf.client.support.utils;
2+
3+
import static org.junit.Assert.assertTrue;
4+
5+
import java.util.List;
6+
import java.util.Map;
7+
8+
import org.junit.Test;
9+
10+
public class ClassUtilsTest {
11+
12+
@SuppressWarnings("unchecked")
13+
@Test
14+
public void testGetValeByType() throws Exception {
15+
assertTrue(ClassUtils.getValeByType(Integer.class, "10086").equals(new Integer(10086)));
16+
assertTrue(ClassUtils.getValeByType(Long.class, "1688").equals(new Long(1688)));
17+
assertTrue(ClassUtils.getValeByType(Boolean.class, "true").equals(new Boolean(true)));
18+
assertTrue(ClassUtils.getValeByType(Double.class, "234.4").equals(new Double(234.4)));
19+
assertTrue(ClassUtils.getValeByType(String.class, "234.4").equals(String.valueOf(234.4)));
20+
List<Integer> list = (List<Integer>) ClassUtils.getValeByType(List.class, "[100,200,300]");
21+
assertTrue(list.contains(new Double(100)));
22+
Map<String, String> map = (Map<String, String>) ClassUtils.getValeByType(Map.class, "{\"name\":\"zxh\",\"city\":\"shenzhen\"}");
23+
assertTrue(map.get("name").equals("zxh"));
24+
}
25+
26+
}

0 commit comments

Comments
 (0)