JavaでJSONを使う

var Json={
encode : function(o) {
var a, i, j;
if (o === null || o === undefined) {
return ‘null’;
} else if (o instanceof Date) {
return ‘”‘ + (new Timestamp(o.getTime())).toString() + ‘”‘;
} else if (o instanceof JavaDate) {
return ‘”‘ + DateUtil.toString(o) + ‘”‘;
} else if (typeof o == ‘number’) {
return isFinite(o) ? String(o) : ‘null’;
} else if (typeof o === ‘boolean’) {
return String(o);
} else if (toString.call(o) === ‘[object Array]’
|| (o instanceof java.lang.Object && o.getClass().isArray())) {
a = new StringBuilder(‘[‘);
j = o.length;
for (i = 0; i < j; i++) {
if (i > 0)
a.append(‘,’);
a.append(Wb.encode(o[i]));
}
a.append(‘]’);
return a.toString();
} else if (toString.call(o) === ‘[object Object]’) {
a = new StringBuilder(‘{‘);
j = false;
for (i in o) {
if (j)
a.append(‘,’);
else
j = true;
a.append(Wb.encode(i));
a.append(‘:’);
a.append(Wb.encode(o[i]));
}
a.append(‘}’);
return a.toString();
} else
return StringUtil.encode(o);
},
decode : function(s, safe) {
try {
return eval(‘(‘ + s + ‘)’);
} catch (e) {
if (safe)
return null;
throw e;
}
}
};

//1.JSONオブジェクトをテキストに変換:
var jsonObject = {‘abc’,123,new Date(),new java.util.Date(),[‘array’,’more’],javaArray,otherObject};
var jsonText = Wb.encode(jsonObject);
Wb.println(request, jsonText);
//2.テキストをJSONオブジェクトに変換

var jsonText = request.getParameter(‘jsonParam’);
var jsonObject = Wb.decode(jsonText);
//3.JSONオブジェクトをトラバース:

var i,n, jsonArray=[1,2,3],jsonObject={a:’foo’,b:’bar’};

for(i in jsonArray)
Wb.println(request,jsonArray[i]);//iはインデックス付き文字0,1,2

for(n in jsonObject)
Wb.println(request,jsonObject[n]);//nはa,b