Skip to content

Instantly share code, notes, and snippets.

@mreis1
Last active November 30, 2016 00:23
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 mreis1/247186f33476200109540b689ae6650a to your computer and use it in GitHub Desktop.
Save mreis1/247186f33476200109540b689ae6650a to your computer and use it in GitHub Desktop.
Java Materials
//import these libraries
import java.util.ArrayList;
import com.google.gson.Gson;
import com.google.gson.JsonArray;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
//create a parser
JsonParser jsonParser = new JsonParser();
//Here we 3 variables containing different JSON structures
//pay attention to each variable name. They are self explanatory
String myJSONArrayOfObjects = "[{"id":1, "taskName":"my task"},{"id":2, "taskName":"my task 2"}]"; //everything that starts and ends with "[" "]" respectively is an array
String myJSONArrayOfStrings = "["1","maria", "foo"]"; //everything that starts and ends with "[" "]" respectively is an array
String myObject = "{"name": "John Doe", "phone": ["+351910000000", "+351960000000"]}"; //this object contains an array of strings in property "phone"
//Here's how to parse the myJSONArrayOfObjects
JsonArray j1 = (JsonArray)jsonParser.parse(myJSONArrayOfObjects);
Gson googleJson = new Gson();
ArrayList myListOfTasks = googleJson.fromJson(jsonArr, ArrayList.class)
//now you can access the list as you would normally
//for example lets count the number of tasks
myListOfTasks.getSize() //outputs 2
var myTask = myListOfTasks.get(1) //returns the index 1
myTask.taskName //outputs "my task 2"
//here's how to parse complext objects
JsonObject j3 = (JsonObject) jsonParser.parse(myJSONOBject);
JsonArray j3Phones = (JsonArray) j3.getAsArray("phone");
Gson googleJson = new Gson(); //we con
ArrayList j3PhoneList = googleJson.parse(j3Phones, ArrayList.class)
Info:
- http://stackoverflow.com/a/18544870/1084568
- https://www.tutorialspoint.com/java/java_arraylist_class.htm
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment