Reputation: 1551
I'm trying to parse a local json file and the output is not what it's supposed to show. I have little experience with Json (and Gson) so I'm unclear as to what the problem is.
Here is the tweet class:
public class tweet {
String from_user;
String from_user_name;
String profile_image_url;
String text;
public tweet(){
//empty constructor
}
}
This is the class where Gson is used:
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);
}
}
Lastly, the .json file which i have saved onto a local directory: http://search.twitter.com/search.json?q=%40android
there are no errors, but the output is:
tweet@3030d5aa
I'm uncertain as to what might be going wrong, so thanks for your guidance!
[Edit: I forgot to add that I have searched SO before and read the related posts. They may be similar but I am not having much luck in piecing the pieces together.]
Upvotes: 2
Views: 6689
Reputation: 29703
System.out.println(J_tweet);
log in console reference on object J_tweet
(tweet@3030d5aa
)
Add method toString()
to your tweet
class
for example
@Override
public String toString()
{
return "from_user: " + from_user + "; from_user_name : " + from_user_name;
}
Upvotes: 1
Reputation: 19414
Strip the results array out of that json, leaving nothing outside the []s.
Then this was just about the least I could modify the code to get it working:
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);
}
}
Upvotes: 2