1 package net.minidev.json.reader;
2
3 import java.io.IOException;
4 import java.lang.reflect.Field;
5 import java.lang.reflect.Method;
6 import java.lang.reflect.Modifier;
7
8 import net.minidev.json.JSONStyle;
9 import net.minidev.json.JSONUtil;
10
11 public class BeansWriter implements JsonWriterI<Object> {
12 public <E> void writeJSONString(E value, Appendable out, JSONStyle compression) throws IOException {
13 try {
14 Class<?> nextClass = value.getClass();
15 boolean needSep = false;
16 compression.objectStart(out);
17 while (nextClass != Object.class) {
18 Field[] fields = nextClass.getDeclaredFields();
19 for (Field field : fields) {
20 int m = field.getModifiers();
21 if ((m & (Modifier.STATIC | Modifier.TRANSIENT | Modifier.FINAL)) > 0)
22 continue;
23 Object v = null;
24 if ((m & Modifier.PUBLIC) > 0) {
25 v = field.get(value);
26 } else {
27 String g = JSONUtil.getGetterName(field.getName());
28 Method mtd = null;
29
30 try {
31 mtd = nextClass.getDeclaredMethod(g);
32 } catch (Exception e) {
33 }
34 if (mtd == null) {
35 Class<?> c2 = field.getType();
36 if (c2 == Boolean.TYPE || c2 == Boolean.class) {
37 g = JSONUtil.getIsName(field.getName());
38 mtd = nextClass.getDeclaredMethod(g);
39 }
40 }
41 if (mtd == null)
42 continue;
43 v = mtd.invoke(value);
44 }
45 if (v == null && compression.ignoreNull())
46 continue;
47 if (needSep)
48 compression.objectNext(out);
49 else
50 needSep = true;
51 String key = field.getName();
52
53 JsonWriter.writeJSONKV(key, v, out, compression);
54
55 }
56 nextClass = nextClass.getSuperclass();
57 }
58 compression.objectStop(out);
59 } catch (Exception e) {
60 throw new RuntimeException(e);
61 }
62 }
63 }
64