2012-10-13 93 views
1

我想解析一個本地json文件,輸出不是它應該顯示的內容。 我對Json(和Gson)沒有什麼經驗,所以我不清楚問題是什麼。解析Json與Java中的Gson

這裏的鳴叫類:

public class tweet { 
     String from_user; 
     String from_user_name; 
     String profile_image_url; 
     String text; 

    public tweet(){ 
     //empty constructor 
      } 
} 

這是GSON使用類:

import java.io.BufferedReader; 
import java.io.FileNotFoundException; 
import java.io.FileReader; 
import com.google.gson.Gson; 

public class tweetfeedreader { 
    public static void main(String args[]) throws FileNotFoundException { 
     Gson gson = new Gson(); 
     BufferedReader bufferedReader = new BufferedReader(new FileReader(
       "C:/Users/LILITH/Desktop/jsonfile.json")); 
     tweet J_tweet = gson.fromJson(bufferedReader, tweet.class); 
     System.out.println(J_tweet); 
    } 
} 

最後,我已經保存到本地目錄中以.json文件: http://search.twitter.com/search.json?q=%40android

沒有錯誤,但輸出是:

[email protected] 

我不確定什麼可能會出錯,所以感謝您的指導!

[編輯:我忘了補充說,我已經搜索過,並閱讀相關的職位。它們可能是相似的,但我並沒有太多的運氣來拼湊在一起。]

回答

1

將結果數組從該json中除去,在[] s之外沒有任何內容。

那麼這只是對至少我可以修改代碼來得到它的工作:

import java.lang.reflect.*; 
import java.io.*; 
import java.util.*; 
import com.google.gson.*; 
import com.google.gson.reflect.*; 

public class tweetfeedreader { 
    public static void main(String args[]) throws IOException { 
    Gson gson = new Gson(); 
    BufferedReader bufferedReader = new BufferedReader(new FileReader(
      "jsonfile.json")); 
    String line; 
    StringBuilder sb = new StringBuilder(); 
    while ((line = bufferedReader.readLine()) != null) sb.append(line); 
    Type tweetCollection = new TypeToken<Collection<tweet>>(){}.getType(); 
    Collection<tweet> tweets = gson.fromJson(line, tweetCollection); 
    for (final tweet t : tweets) System.out.println(t.text); 
    } 
} 
+0

Ju st試了一下。它現在給我一個null的輸出 –

+0

你能提供jsonfile.json的內容嗎? – rich

+0

我從http://search.twitter.com/search.json?q=%40android複製了一切到jsonfile.json –

1
System.out.println(J_tweet); 

日誌中的對象J_tweet[email protected]
Add方法toString()控制檯參考您的tweet
例如

@Override 
public String toString() 
{ 
    return "from_user: " + from_user + "; from_user_name : " + from_user_name;  
} 
+0

啊謝謝,這也起作用了。 –