18 package org.turro.elephant.impl.util;
20 import java.lang.reflect.Array;
21 import java.util.Iterator;
22 import java.util.List;
30 private StringBuffer result;
38 public String
toJSON(Object javaObject) {
39 result =
new StringBuffer();
40 processObject(javaObject);
41 return result.toString();
44 private void processObject(Object javaObject) {
45 if(javaObject instanceof Array) {
46 processArray(javaObject);
48 else if(javaObject instanceof Map) {
49 processMap(javaObject);
51 else if(javaObject instanceof List) {
52 processList(javaObject);
54 else if(javaObject instanceof String) {
55 processString(javaObject);
57 else if(javaObject instanceof Number) {
58 processNumber(javaObject);
60 else if(javaObject instanceof Character) {
61 processCharacter(javaObject);
65 private void processArray(Object javaObject) {
66 Array array = (Array)javaObject;
69 for(
int i = 0; i < Array.getLength(array); i++) {
70 if(!first) result.append(
",");
71 processObject(Array.get(array, i));
77 private void processMap(Object javaObject) {
78 Map map = (Map)javaObject;
79 Iterator it = map.keySet().iterator();
84 if(!first) result.append(
",");
89 processObject(map.get(obj));
96 private void processList(Object javaObject) {
97 List list = (List)javaObject;
98 Iterator it = list.iterator();
100 boolean first =
true;
101 while(it.hasNext()) {
102 if(!first) result.append(
",");
103 processObject(it.next());
109 private void processString(Object javaObject) {
110 result.append(
"\"" + (String)javaObject +
"\"");
113 private void processNumber(Object javaObject) {
114 result.append(
"\"" + ((Number)javaObject).toString() +
"\"");
117 private void processCharacter(Object javaObject) {
118 result.append(
"'" + ((Character)javaObject).toString() +
"'");
String toJSON(Object javaObject)