1

以下 java 块处理 simplejson 和 string/JSONArray 转换。我在 centos 上运行 jre 1.6。

我的目标,试图弄清楚如何处理空数组作为输入文本,并转换为 simplejson JSONArray。

块中的“s”代表测试应用程序的有效输入样本。

.
.
.
import org.json.simple.*;

    String s="[0,{\"1\":{\"2\":{\"3\":{\"4\":[5,{\"6\":7}]}}}}]";
    String s="[null]";

    Object objm=JSONValue.parse(s);
    JSONArray array=(JSONArray)objm;
    System.out.println(array.size();

//the above works as expected...
however, if i use a string of

    String s="[]";

i get an error:
    Exception in thread "main" java.lang.ClassCastException: 
    java.lang.String cannot be cast to org.json.simple.JSONArray

所以,我试图了解如何使用“[]”而无需检查文本以转换为 [] 数组...

有什么想法吗??

谢谢

4

1 回答 1

1

只需检查它:。

if (!"[]".equals(s)) {
  Object objm=JSONValue.parse(s);
  JSONArray array=(JSONArray)objm;
  System.out.println(array.size();
} else {
  // ..
}
于 2012-01-04T22:48:06.283 回答