0

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.

5
  • why not try using Gson?
    – Rahul
    Apr 29, 2013 at 7:15
  • I have also seen that but my case is different where i create object using Reflection and convert the object to JSON or JSON Array. Apr 29, 2013 at 7:16
  • 1
    if you notice your output, u can see [[ double square braces, which means the JSONSerializer has already converted it to an JSONArray. You needn't do it manually. And regd the null, make sure that your obj passed to the method convertPlainObjectToJSON is not null.
    – Rahul
    Apr 29, 2013 at 7:19
  • yes, the object i pass is null, because i just want to pass the empty json string/Array Apr 29, 2013 at 7:26
  • An empty array is something different from null. You can e.g. create one using new Object[0]. @R.J, your comment seems like it would make a good answer, do you want to post it as such?
    – MvG
    Apr 29, 2013 at 10:15

1 Answer 1

1

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!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.