Reputation: 45
So the app I'm currently working with is going to be doing a lot of requests that all return json, would it be appropriate to create a class that holds the properties for each specific request thats going to return the json that can be converted into the properties of that class?
For example, say I have 2 requests, one that returns a firstname, a surname and a job role, and I have another request that returns a business name, business location and business postcode, would it be OK to do:
class BusinessRetrieval {
public string BusinessLocation{ get; set; }
public string BusinessPostCode { get; set; }
}
class EmployeeRetrieval {
public string Firstname { get; set; }
public string Surname { get; set;}
public string Postcode { get; set; }
}
So now I have 2 classes that outline the properties that are going to be sent back once the request is made, now is it OK to just do:
BusinessRetrieval business = (BusinessRetrieval)JsonConvert.DeserializeObject(businessResponse, typeof(BusinessRetrieval));
EmployeeRetrieval employee = (EmployeeRetrieval)JsonConvert.DeserializeObject(employeeResponse, typeof(EmployeeRetrieval));
What I'm asking here is this an OK to go around doing this? I'm going to be dealing with a lot of requests (10-15) and I plan on making a class for each that outline the properties that each response will give back, I feel as if this would be a nice way to structure it.
Is this OK?
Upvotes: 0
Views: 55
Reputation: 191
Yes it is the only reasonable way to handle it to make your code type safe.
Though you cannot cast the result of the non generic DeserializeObject
to the type of your choice - it will throw an Exception.
Instead use the Generic version of DeserializeObject:
BusinessRetrieval business = JsonConvert.DeserializeObject<BusinessRetrieval>(businessResponse);
EmployeeRetrieval employee = JsonConvert.DeserializeObject<EmployeeRetrieval>(employeeResponse);
Upvotes: 1
Reputation: 1308
I think it is not only okay to do, I think it would be a best practice so you can pass that object through any methods without any problems.
Upvotes: 0