-
Notifications
You must be signed in to change notification settings - Fork 6
/
How to Parse JSON from Java Object
45 lines (45 loc) · 1.17 KB
/
How to Parse JSON from Java Object
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
private static void BeanToJson(Object object, JSONObject json) throws Exception
{
if(object != null)
{
PropertyDescriptor[] property = null;
property = Introspector.getBeanInfo(object.getClass(),Object.class).getPropertyDescriptors();
for(PropertyDescriptor each : property)
{
try
{
String propertyName = null;
Object obj = each.getReadMethod().invoke(object);
if(ClassUtils.isPrimitiveOrWrapper(obj.getClass()) || obj instanceof String)
{
propertyName = each.getName();
json.put(propertyName,obj);
}
else if(obj instanceof ArrayList)
{
ArrayList<?> arrayList = (ArrayList<?>) obj;
JSONArray jsonArray = new JSONArray();
propertyName = each.getName();
for(int index =0; index < arrayList.size(); index++)
{
JSONObject newJson = new JSONObject();
BeanToJson(arrayList.get(index),newJson);
jsonArray.put(newJson);
}
json.put(propertyName, jsonArray);
}
else
{
JSONObject newJson = new JSONObject();
propertyName = each.getName();
BeanToJson(obj,newJson);
json.put(propertyName,newJson);
}
}
catch(Exception e)
{
e.printStackTrace();
}
}
}
}