Skip to content

Instantly share code, notes, and snippets.

@schwartzadev
Created February 21, 2017 18:40
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save schwartzadev/c9ef1f1079f506c0022fd4725e583382 to your computer and use it in GitHub Desktop.
Save schwartzadev/c9ef1f1079f506c0022fd4725e583382 to your computer and use it in GitHub Desktop.
Gson Isn't Working
import com.google.gson.Gson;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonParser;
import com.google.gson.stream.JsonReader;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
public class JsonParserDemo {
private String jsonSource;
private boolean sourceFromFile;
public JsonParserDemo(String jsonSource, boolean sourceFromFile){
this.jsonSource = jsonSource;
this.sourceFromFile = sourceFromFile;
}
public static void main(String[] args){
JsonParserDemo jsonParserDemo =
new JsonParserDemo("/home/andrew/IdeaProjects/Article-Saver/json.json", true);
try(JsonReader jsonReader = jsonParserDemo.getJsonReader()){
jsonReader.setLenient(true);
Gson myGson = new Gson();
JsonParser jsonParser = new JsonParser();
JsonArray userArray = jsonParser.parse(jsonReader).getAsJsonArray();
List twitterUsers = new ArrayList<>();
for ( JsonElement aUser : userArray ){
Source aSource = myGson.fromJson(aUser, Source.class);
twitterUsers.add(aSource);
}
for ( Object tUser : twitterUsers){
System.out.println(tUser);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
/**
* Obtain the JsonReader for the given source details.
* @return the JsonReader instance
* @throws FileNotFoundException
*/
private JsonReader getJsonReader () throws FileNotFoundException{
JsonReader reader = null;
if (sourceFromFile){
reader = new JsonReader(
new InputStreamReader(new FileInputStream(this.jsonSource)));
}
return reader;
}
}
class Source{
private String title;
private String author;
public Source(){
}
@Override
public String toString(){
return "Name: "+this.title+"\n" +
"Screen Name: "+this.author+"\n";
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment