Skip to content

Instantly share code, notes, and snippets.

@codeamt
Last active December 13, 2018 01:24
Show Gist options
  • Save codeamt/1f8a23a6454e67944da1f327389ce288 to your computer and use it in GitHub Desktop.
Save codeamt/1f8a23a6454e67944da1f327389ce288 to your computer and use it in GitHub Desktop.
package com.udacity.sandwichclub.utils;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
public class JsonUtils {
public static Sandwich parseSandwichJson(String json) {
try {
/* Step One: Convert json string to JSON object */
JSONObject base = new JSONObject(json);
/* Step Two: Parse the Base Object's Keys Into Autonomous Objects/Strings for Serializing */
// Handle anomolies first
// Parsing the name key
// Coerce name key to JSON object called "name"
JSONObject name = base.getJSONObject("name");
// Access the mainName key of the name object store it's value as String
String mainName = name.getString("mainName");
// Coerce the alsoKnownAs key to a JSON array called "altNames"
JSONArray altNames = name.getJSONArray("alsoKnownAs");
// Instantiate Array Literal for Alt Names called "altNamesList"
ArrayList<String> altNamesList = new ArrayList<>();
// Loop through altNames JSON array
for(int i=0; i<altNames.length(); i++) {
// Add each item in altNames to altNamesList
altNamesList.add(altNames.getString(i));
}
// Parsing the ingredients key
// Coerce ingredients key to a JSON array called "ingredients"
JSONArray ingredients = base.getJSONArray("ingredients");
// Instantiate Array Literal for Ingredients called "ingredientsList"
ArrayList<String> ingredientsList = new ArrayList<>();
// Loop through ingredients JSON array
for(int i=0; i<ingredients.length(); i++) {
// Add each item in ingredients to the ingredientsList
ingredientsList.add(ingredients.getString(i));
}
// Parsing keys with primitive assignments
// Access the placeOfOrigin key of the base object, store the value as String
String placeOfOrigin = base.getString("placeOfOrigin");
// Access the image key of the base object, store the value as String
String image = base.getString("image");
// Access the description key from the base object, store the value as String
String description = base.getString("description");
} catch (JSONException e) {
/* Print Any Errors */
e.printStackTrace();
}
return null;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment