- package jp.co.qualica.kcm.action.common;
- import java.lang.reflect.Field;
- import java.lang.reflect.Method;
- import java.util.List;
- public class JSONUtil {
- public static <T> String fromList(List<T> list) throws Throwable {
- StringBuilder json = new StringBuilder();
- if (list == null || list.size() == 0) {
- return null;
- }
- json.append("[");
- for(int i = 0; i < list.size(); i++) {
- json.append("{");
- T t = list.get(i);
- Class clazz = t.getClass();
- Field[] fields = t.getClass().getFields();
- for(int j=0; j<fields.length; j++) {
- Field field = fields[j];
- String strFields = field.getName();
- String getMethodName = "get"+ strFields.substring(0, 1).toUpperCase() + strFields.substring(1);
- Method method =clazz.getMethod(getMethodName, new Class[]{});
- Object value = method.invoke(t, new Object[]{});
- json.append("\"" + strFields + "\"" + ":" + "\"" + value + "\"");
- if (j < fields.length - 1) {
- json.append(",");
- }
- }
- json.append("}");
- if (i < list.size() - 1) {
- json.append(",");
- }
- }
- json.append("]");
- return json.toString();
- }
- }
// 如果是你现在的提问,你的 string 是 '*****'
<script type=
"text/javascript"
>
window.onload =
function
(){
var
itemString =
"'{id:\"item1\",num:1},{id:\"item2\",num:2}'"
;
if
(itemString.length>2){
itemString = itemString.substring(1,itemString.length-1);
itemString = eval(
'(['
+ itemString +
'])'
);
alert(itemString);
}
}
</script>
// 这是对于你第一个发的问题的,确保你的问题是正确的,那【两边有单引号】
// 也就是 var str = "'{ *** }'";
<script type=
"text/javascript"
>
window.onload =
function
() {
// 假设你的 string 如你所给的,是 ‘{string}’
var
itemString =
"‘{id:'item1',num:1,id:'item2',num:2,id:'item3',num:3}’"
;
if
(itemString.length > 4) {
// 先把 ‘{}’两个给去掉,剩下 id:'',num:1, id:'',num:2 ***
itemString = itemString.substring(2, itemString.length - 2);
// 还要假设你的数据一定是规则的 id:'',num:1 每2个是一组,都是用 , 来分隔的
// 这样就切出来了 id:'' num:1 id;'' num:2 的数组
var
arrs = itemString.split(
','
);
var
arrlen = arrs.length;
var
result =
""
;
for
(
var
i = 0; i < arrlen; i = i + 2) {
// 如果 result 不为空,则是已经拼接过 { id:'',num:* } 了,再拼接一个则要加上 ,
if
(result !=
""
) {
result +=
","
;
}
// 最终结果拼接为 { id:'',num:* } , { id:'',num:* }
result +=
"{"
+ arrs[i] +
","
+ arrs[i + 1] +
"}"
;
}
// 最后拼接总的字符串 [ + { id:'',num:* } , { id:'',num:* } + ]
result =
"["
+ result +
"]"
;
alert(result);
}
}
</script>