2012-08-06 67 views
1

我有多個JSON在一個文件input.txt中:多JSON解析Java中

{"Atlas":{"location":"lille","lat":28.4,"long":51.7,"country":"FR"}} 
{"Atlas":{"location":"luxum","lat":24.1,"long":54.7,"country":"LU"}} 
{"Atlas":{"location":"ghent","lat":28.1,"long":50.1,"country":"BE"}} 

注意:他們不是以逗號分隔(「」),他們是不是數組。這些是有效的單個JSON。

我相信應該有可能得到一個輸出。

我的代碼下面既不顯示錯誤,也沒有輸出?這裏有什麼問題?

這是我的代碼:

class Loc{ 
     private String location; 
     private Long lat; 
     private Long long; 
     private String country; 

    //getter and setter methods 
    } 
    public class JsonReader { 
     public static void main(String[] args) throws ParseException { 

      try { 
       BufferedReader br= new BufferedReader(new FileReader("C:\\input.txt")); 
       String jsonTxt = IOUtils.toString(br);     
       JSONParser parser = new JSONParser();        
       String line=null; 
       while ((line = br.readLine()) != null) 
       { 
        Loc emp = (Loc) (new JSONParser().parse(jsonTxt)); 
        System.out.printf("%s",emp.getLocation()); 
        System.out.printf("\t%d",emp.getlat()); 
        System.out.printf("\t%d",emp.getLong()); 
        System.out.printf("\t%s",emp.getCountry()"\n"); 
      } 
    }catch (FileNotFoundException e) { 
      e.printStackTrace(); 
     } catch (IOException e) { 
      e.printStackTrace(); 
     } 

}} 
+0

在它看起來像你在錯誤的情況下打開每個記錄乍看之下。 – 2012-08-06 16:46:24

回答

1

要傳遞的IOUtils.toString(BufferedReader)結果到JSONParser。如您所知,整個文件內容不是有效的JSON。假設每行都是有效的JSON,請將數據逐行傳遞給解析器。您的代碼已經設置完成。

在您的循環中,將line傳遞給解析器,並刪除IOUtils的東西。

我假定JSONParserorg.json.simple.parser.JSONParser。如果是這樣,它將不會爲您構建您的對象,而無需您做更多工作:它僅解析JSON並返回JSONObjects,JSONArray等的樹。請參閱hereJSONAwarehere的位。

或者查看JacksonGSON以將您的JSON解析爲java對象。

此外,您的Loc成員不能被命名爲long:這是一個java關鍵字,並且會阻止您的代碼編譯。

+0

我在線程「main」中收到此錯誤異常java.lang.ClassCastException:org.json.simple.JSONObject無法轉換爲JsonSample.Employ \t at JsonSample.JsonReader.main(JsonReader.java:68) – labbyfrost 2012-08-06 06:15:17

2

你解析錯誤的東西。你應該解析line而不是jsonTextline是從BufferedReader中讀入的實際行。

1

看起來你需要進行解析線,不jsonTxt

Loc emp = (Loc) (new JSONParser().parse(jsonTxt));