2017-06-20 39 views
1

我正在使用Gson庫將對象的JSON數組轉換爲字符串。 但我得到這個錯誤無法從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); 

它是我用正確的結果在YouTube上(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); 

,然後遍歷DataIntent爲例類的列表:

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

Heyy @DavisMolinari謝謝你們的建議,因爲現在的錯誤已經走了,但在我加入一個「如果」循環(如這是在視頻中)我不能這樣做..因爲我想遍歷並獲得expr的所有值 – shubham

+0

@shubham你應該注意他在視頻中做了什麼並正確地重現它:他有Result類有一個List Todo物件。他對結果進行反序列化並遍歷其Todo對象列表。你有Example類是它的結果,你的DataIntent是它的Todo。所以你必須反序列化爲Example,然後循環訪問DataIntent列表 –

+0

@shubham我編輯答案 –

相關問題