i try to convert a class object which are generated via Reflection and convert them to JSON string. following is my methods
public Object creatObjectAsString(String className) {
Object objects = null;
try {
objects = java.lang.reflect.Array.newInstance( Class.forName(className), 1);
//System.out.println(objects.toString());
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
return objects ;
}
public String convertPlainObjectToJSON( Object obj,boolean isArray){
String jsonString="",tempJSON="";
JSONSerializer serializer = new JSONSerializer();
tempJSON = serializer.serialize(obj);
if(isArray){
jsonString="["+tempJSON+"]";
}else{
jsonString=tempJSON;
}
return jsonString;
}
I have hard coded the following lines since i did not know how to create JSON Array which is not the correct way of programming.
if(isArray){
jsonString="["+tempJSON+"]";
}else{
jsonString=tempJSON;
}
when i printed the convertPlainObjectToJSON
result of method i get the following [[null]]
which is not expected.
what is the mistake i make.
Please correct me.
If you notice your output, you can see [[
( double square braces ), which means the JSONSerializer
has already converted it to an JSONArray
. Therefore, you needn't do it again manually.
And regarding the null
between them, it is because you're passing null
to the convertPlainObjectToJSON
. Send a newly created object array ( as @MvG mentioned), new Object[0]
, and you'll get what you want!
Always remember that blank
and null
are not the same!
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.