-
-
Save schwartzadev/c9ef1f1079f506c0022fd4725e583382 to your computer and use it in GitHub Desktop.
Gson Isn't Working
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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