In this post, I wondered how I should encapsulate the JSON filling in of my Model Exercise Database.
The solution I have come up with is as follows:
- I created a new abstract class: AbstractSourceFactory.cs
public abstract class AbstractSourceFactory { public abstract Task<List<ModelExercise>> ExercisesGet(string url = null); }
- Simple enough one method that returns a list of model Exercises an abstract class is nothing without it’s implementation:
public class wgerSourceFactory : AbstractSourceFactory { private string _URL = "https://wger.de/api/v2/exercise/?format=api&language=2"; private List<ModelExercise> _exercises = new List<ModelExercise>(); private HttpClient _client = new HttpClient(); public async override Task<List<ModelExercise>>;</pre> ExercisesGet() { string next; next = await ParseJSON(); while (next != null) { await ParseJSON(next); } return _exercises; } private async Task<string> ParseJSON(string url= null) { if (url == null) { url = _URL; } var content = await _client.GetStringAsync(_URL); var response = JsonConvert.DeserializeObject<_response>(content); var exercises = response.results; foreach (var exercise in exercises) { _exercises.Add( new ModelExercise { Id = exercise.id, Name = exercise.name, Description = exercise.description, } ); } return response.next; }
- I dont all the information that the API delivers so I made a small private class:
private class _wgerExercise { public int id { get; set; } public string license_author { get; set; } public int status { get; set; } public string description { get; set; } public string name { get; set; } public string name_original { get; set; } public string creation_date { get; set; } public string uuid { get; set; } public int license { get; set; } public int category { get; set; } public int language { get; set; } public List<int> muscles { get; set; } public List<int> muscles_secondary { get; set; } public List<int> equipment { get; set; } } private class _response { public int count { get; set; } public string next { get; set; } public string previous { get; set; } public List<_wgerExercise> results { get; set; } }
To store the JSON results
- And now in my DataStore Class I have a method:
public async Task FillExercisesFromDataStore(AbstractSourceFactory factory) { List<ModelExercise> exercises = await factory.ExercisesGet(); foreach (var exercise in exercises) { await _connection.InsertAllAsync(exercises); } }
- Now in the future, I can pass any factory I want and I can still get all the data in 🙂 super proud of myself for not coding like a chump 😉
Tomorrow I’ll build a page to display it all and it will come down crashing on my head with all the mistakes I made, but whatever! Today was a good day!