2017-06-20 7 views
1

Gsonライブラリを使用して、JSON配列の配列をStringに変換しています。 しかし、このエラーが発生しましたDataIntentから結果にキャストできません!!<Type>からGsonを使用して結果にキャストできません

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(); 
    } 
    } 
} 

私は何が間違っているのか分からないのですか?私はプログラミングの初心者です。 私はそれは私が使用しています右の結果であり、私は

org.junit.runner.Result result = (org.junit.runner.Result)gson.fromJson(br, DataIntent.class); 

上の問題を取得していますユーチューブ(This link)

上の映像の上にこれを見てきました?他の解決策は何ですか?オブジェクトのJSONArrayを解析してキーを取得できます: 'expr'の値 助けてください!

答えて

0

gson.fromJson json文字列をパラメータとして指定したクラスのオブジェクトに逆シリアル化して、ケースにDataIntent.classを追加します。 あなたがリンクしたビデオでは、Resultがjsonの文字列を逆シリアル化するクラスです。 実際に文は次のとおりです。

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

不要キャストはありません、あなたはちょうどあなたがfromJsonメソッドにパラメータとして渡している同じタイプのdesarializationの結果でインスタンス化する変数を定義する必要があります。あなたのコメントに基づいて

DataIntent di = gson.fromJson(br, DataIntent.class); 

編集: あなたはあなたの例のクラスにデシリアライズする必要があります

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

、その後、ExampleクラスのDataIntentのリストをループ:

for(DataIntent di : example.getDataIntents()) 
+0

Heyy @DavisMolinariありがとうご提案のため、エラーがなくなった今のように、しかし、私は「もし」ループを追加していながら、(など私はそれを行うことはできません..繰り返してexprのすべての値を取得したいのですが) – shubham

+0

@shubhamビデオで何をやっているのか注意して、正しく再現する必要があります。リストにはResultクラスがありますTodoオブジェクトの彼は結果をデシリアライズし、Todoオブジェクトのリストをループします。その結果であるExampleクラスがあり、DataIntentがそのTodoです。だから例を逆シリアル化してDataIntentのリストをループする必要があります –

+0

@shubham答えを編集しました –

関連する問題