【问题标题】:checking if a string that is a array of JSONObject is empty检查作为 JSONObject 数组的字符串是否为空
【发布时间】:2018-02-26 23:41:51
【问题描述】:

所以我收到了来自 api 调用的 jsonobject。

在 jsonobject 内部有一个字段可以保存 JSONObjects 数组

例如

{ "订单":[]}

如何检查数组是否为空?

JSONSimple 库

JSONObject[] check = new JSONObject[0];

JSONObject g = new JSONObject();
g.put("test", check);

System.out.println(((List<JSONObject>)g.get("test")).size());

实际结果:错误

期望的结果:json[]的大小

谢谢

【问题讨论】:

  • 首先,名字是"order",而不是"test"。其次,数组是JSONArray,而不是List
  • org.json.simple.JSONArray 实现List&lt;Object&gt;。见here

标签: java json-simple


【解决方案1】:

您不能将 JsonObject (JSONObject[]) 数组转换为 JSONObject (List) 列表 - 它们是具有 2 个不同层次结构的 2 个不同的类。将其转换为 JSONObject[],因为现在它是一个数组而不是列表,所以使用 length,而不是 size()。

    JSONObject[] check = new JSONObject[0];

    JSONObject g = new JSONObject();
    g.put("test", check);

    //System.out.println(((List<JSONObject>) g.get("test")).size());
    System.out.println(((JSONObject[]) g.get("test")).length);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-08-09
    • 2015-06-12
    • 1970-01-01
    • 2015-06-05
    • 2014-09-22
    • 1970-01-01
    • 2016-06-05
    相关资源
    最近更新 更多