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 com.udacity.sandwichclub.model.Sandwich;
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 */
// Handle anomolies first
JSONObject name = base.getJSONObject("name");
String mainName = name.getString("mainName");
JSONArray altNames = name.getJSONArray("alsoKnownAs");
ArrayList<String> altNamesList = new ArrayList<>();
for(int i=0; i<altNames.length(); i++) {
altNamesList.add(altNames.getString(i));
}
JSONArray ingredients = base.getJSONArray("ingredients");
ArrayList<String> ingredientsList = new ArrayList<>();
for(int i=0; i<ingredients.length(); i++) {
ingredientsList.add(ingredients.getString(i));
}
// Parsing keys with primitive assignments
String placeOfOrigin = base.getString("placeOfOrigin");
String image = base.getString("image");
String description = base.getString("description");
// Step Three: Finally, return a new Sandwich Object
return new Sandwich(mainName, altNamesList, placeOfOrigin, description, image, ingredientsList);
} 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