首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >JSONObject到JSONObject类强制转换异常

JSONObject到JSONObject类强制转换异常
EN

Stack Overflow用户
提问于 2017-06-19 07:06:56
回答 1查看 1.1K关注 0票数 1

我正试图解析我的JSONObject以获取JSON的数据。

但问题是,JSONParser是org.json.simple.JSONParser中的一个类,JSONObject是org.json.JSONObject中的一个类。

我在org.json中找不到任何解析器来避免类强制转换异常!

我们还有别的办法来解决这些问题吗.?

还是我走错了方向?请建议

我的JSON看起来像:

代码语言:javascript
复制
{
 "dataIntents": [
 {
  "intent": "muster.policy.daily",
  "expr": "Am I supposed to register my attendance daily?"
 },
 {
  "intent": "leave.probation",
  "expr": "An employee is eligible for how many leaves in 1st year ??"
 },
 {
  "intent": " leave.resigned ",
  "expr": "Are resigned employees eligible for pro rata leave credit"
 },
 {
  "intent": " muster.deadline.submission ",
  "expr": "By when should I get my pending leave/Emuster applications 
 approved?"
  }
 ]
}

我的主修班:

代码语言:javascript
复制
public class DLMain {

public static void main(String[] args) {

try {
        JSONParser parser = new JSONParser();
        Object obj = 
        parser.parse(newFileReader("/home/cmss/Downloads/data.json"));
        org.json.JSONObject dataObject = (org.json.JSONObject)obj;
        System.out.println(dataObject);
        org.json.JSONArray getArray = 
        dataObject.getJSONArray("dataIntents");

        for (int i = 0; i < getArray.length(); i++) {
            org.json.JSONObject objects = getArray.getJSONObject(i);
            String a = objects.getString("expr");
        }
        System.out.println();
    } catch (Exception e) {
        System.out.println(e);
    }
  }
}

我需要JSONObject或字符串中"expr“键的所有值。

(预先欣赏到的帮助:)

EN

回答 1

Stack Overflow用户

发布于 2017-06-19 07:14:47

你为什么不用一个POJO来做呢?

到目前为止,您的Json是一个意图列表,您可以有如下内容:

代码语言:javascript
复制
public class Intents {
    private List<Intent> dataIntents;
}

还有另一个

代码语言:javascript
复制
public class Intent {
    private String intent;
    private String expr;
}

(请生成构造函数和getter setter)

然后可以直接使用ObjectMapper,避免了所有难看的JSON解析。

希望能帮上忙!

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/44624243

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档