无法使用Gson

时间:2017-06-20 09:18:39

标签: java json gson

我正在使用Gson库将我的JSON对象数组转换为String。 但是我收到无法从DataIntent转换为结果 !!

的错误

DataIntent是POJO类的名称。

data.json

`{
 "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 ??"
   }
  ]
}`

POJO课程:

 public class DataIntent {

 private String intent;
 private String expr;

 //getters and setters

 }'

示例类

 public class Example {

 private List<DataIntent> dataIntents = null;

 public List<DataIntent> getDataIntents() {
    return dataIntents;
 }

 public void setDataIntents(List<DataIntent> dataIntents) {
    this.dataIntents = dataIntents;
 }

 }

主要课程:

   public class JSONMain {
   public static void main(String[] args) {
    Gson gson = new Gson();
    BufferedReader br = null;
    try {
        br = new BufferedReader(new FileReader("data.json"));
        org.junit.runner.Result result = (org.junit.runner.Result) 
        gson.fromJson(br, DataIntent.class);

    } catch (FileNotFoundException e) {
        e.printStackTrace();
    }
  }
}

我不知道我做错了什么?因为我是编程新手。 我在youtube上发布了一段视频(This link)

我在

上遇到问题
org.junit.runner.Result result = (org.junit.runner.Result)gson.fromJson(br, DataIntent.class);

这是我正在使用的正确结果吗?或者其他解决方案是什么,所以我可以解析我的JSONArray对象获取密钥:'expr'的值 请帮忙!!

1 个答案:

答案 0 :(得分:0)

gson.fromJson将json字符串反序列化为您在参数中提供的类的对象DataIntent.class。 在您关联的视频中,Result是他要将json字符串反序列化为的类。 实际上声明是:

Result result = gson.fromJson(br, Result.class)

不需要强制转换,您只需要定义要实例化的变量,并将您作为参数传递给fromJson方法的相同类型的desarial化结果:

DataIntent di = gson.fromJson(br, DataIntent.class);
根据您的评论

修改: 您应该反序列化到Example类:

Example example = gson.fromJson(br, Example.class);

然后循环遍历Example类的DataIntent列表:

for(DataIntent di : example.getDataIntents())
相关问题