2017-03-01 161 views
3

我想用Java使用GSON庫讀取此JSON文件。 我是使用gson libray的新手。有人請糾正我的代碼 我的JSON文件看起來像這樣:如何使用GSON庫將json文件讀取到java中

{ 
"tableRows":[ 
    { 
    "id":"100", 
    "mailContent":"Test mail content 123", 
    "sentiment":"0" 
    }, 
    { 
    "id":"200", 
    "mailContent":"Test mail content 123", 
    "sentiment":"0" 
    }, 
    { 
    "id":"300", 
    "mailContent":"Test mail content 123", 
    "sentiment":"0" 
    } 
] 
} 

這是我寫的閱讀該文件中的Java代碼:

import java.io.FileNotFoundException; 
import java.io.FileReader; 
import com.google.gson.JsonArray; 
import com.google.gson.JsonElement; 
import com.google.gson.JsonIOException; 
import com.google.gson.JsonParser; 
import com.google.gson.JsonSyntaxException; 
import com.google.gson.JsonObject; 
public class Sample { 
public static void main(String[] args) { 

    JsonParser parser = new JsonParser(); 
    try { 
     JsonElement jsontree = parser.parse(
      new FileReader(
       "/Users/kesavan-4688/Desktop/JSP-Eclipse/Sample/src/Demo/sample.json" 
      ) 
     ); 
     JsonElement je = jsontree.getAsJsonObject(); 
     JsonArray ja = je.getAsJsonArray(); 
     for (Object o : ja) 
     { 
      JsonObject person = (JsonObject) o; 

      String id = person.get("id").getAsString(); 
      System.out.println(id); 

      String mail = person.get("mailcontent").getAsString(); 
      System.out.println(mail); 

      String sentiment = person.get("sentiment").getAsString(); 
      System.out.println(sentiment); 
     } 
    } 
    catch (JsonIOException e) { 
     e.printStackTrace(); 
    } catch (JsonSyntaxException e) { 
     e.printStackTrace(); 
    } catch (FileNotFoundException e) { 
     e.printStackTrace(); 
    } 
} 

} 

,但我得到以下異常:

Exception in thread "main" java.lang.IllegalStateException: This is not a JSON Array. 
at com.google.gson.JsonElement.getAsJsonArray(JsonElement.java:106) 
at Demo.Sample.main(Sample.java:18) 
+0

的可能重複http://stackoverflow.com/questions/29965764/how-to-parse-json -file與 - GSON – freedev

回答

3

您嘗試將JsonObject轉換爲JsonArray無法正常工作,您需要先獲取根JsonObject然後再使用getAsJsonArray(String memberName)獲取屬性tableRows作爲JsonArray爲未來:

... 
// Get the root JsonObject 
JsonObject je = jsontree.getAsJsonObject(); 
// Get the property tableRows as a JsonArray 
JsonArray ja = je.getAsJsonArray("tableRows"); 
for (Object o : ja) { 
    ... 
    // Warning JSON is case sensitive so use mailContent instead of mailcontent 
    String mail = person.get("mailContent").getAsString(); 
    ... 
} 

輸出:

100 
Test mail content 123 
0 
200 
Test mail content 123 
0 
300 
Test mail content 123 
0