2

ローカルの json ファイルを解析しようとしていますが、出力が表示されるはずのものではありません。私は Json (および 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

エラーはありませんが、出力は次のとおりです。

tweet@3030d5aa

何がうまくいかないのかわからないので、ご指導ありがとうございます!

[編集: SO を以前に検索し、関連する投稿を読んだことを追加するのを忘れていました。それらは似ているかもしれませんが、ピースをつなぎ合わせるのにあまり運がありません.]

4

2 に答える 2

2

結果の配列をその json から取り除き、[] の外側には何も残しません。

次に、これは、コードを変更して機能させることができる最小限のものでした。

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);
  }
}
于 2012-10-13T20:43:27.127 に答える
1
System.out.println(J_tweet); 

オブジェクトのコンソール参照にログインしますJ_tweettweet@3030d5aa) たとえば、クラス
にメソッドを追加toString()しますtweet

@Override 
public String toString()  
{  
   return "from_user: " + from_user + "; from_user_name : " + from_user_name;     
}
于 2012-10-13T22:07:25.497 に答える