简体   繁体   English

JSON-将对象转换为JSON数组

[英]JSON - Convert Object to JSON Array

i try to convert a class object which are generated via Reflection and convert them to JSON string. 我尝试转换通过反射生成的类对象,并将它们转换为JSON字符串。 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. 由于我不知道如何创建JSON Array(这不是正确的编程方式),因此我对以下几行进行了硬编码。

if(isArray){
    jsonString="["+tempJSON+"]";
}else{
    jsonString=tempJSON;
}

when i printed the convertPlainObjectToJSON result of method i get the following [[null]] which is not expected. 当我打印方法的convertPlainObjectToJSON结果时,得到以下[[null]] ,这是不期望的。

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 . 如果您注意到输出,则可以看到[[双括号 ),这意味着JSONSerializer已将其转换为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 . 关于它们之间的null ,是因为您要将null传递给convertPlainObjectToJSON Send a newly created object array ( as @MvG mentioned), new Object[0] , and you'll get what you want! 发送一个新创建的对象数组( 如@MvG所述), new Object[0] ,您将得到想要的!

Always remember that blank and null are not the same! 永远记住, blanknull是不一样的!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM