Sunday, 1 September 2013

ViewModel and JSON

ViewModel and JSON

Problem Background :
I have a ViewModel called VM_a. Its content will be serialized into JSON
string on form submission, and then saved into DB - 1 form for each
record.
When I choose to display all records of VM_a, I will deserialize the
records of VM_a, populate them into List and then show them in JQGrid.
Below are the snippets which I've used to deserialize, and the actual
ViewModel.
ViewModel :
public class VM_a
{
public string var_1 { get; set; }
public string var_2 { get; set; }
public string var_3 { get; set; }
public string var_4 { get; set; }
}
Deserialization :
public static T Deserialize<T>(object json)
{
if (typeof(T).IsAssignableFrom(typeof(T)))
{
object res = JsonConvert.DeserializeObject(json.ToString(), new
JsonSerializerSettings()
{
ContractResolver = resolver,
TypeNameHandling = TypeNameHandling.All
});
return (T)res;
}
throw new NotImplementedException("Type is not assignable.");
}
Usage of deserialization :
VM_a instanceVM = Project.Shared.JSONHelper.Deserialize<VM_a>(json_string);
Problem 1 :
I want to display the data in JQGrid and have its column dynamically
generated.
By dyamically generated, I mean each form (or VM) will have their
corresponding set of fields that will be displayed, which is stored in DB.
Example :
VM_a which has 4 fields, will be displayed in just 3 fields : var_1, 3,
and 4.
Another VM, called VM_b which has 7 fields, will be displayed in just 5
fields : 1,3,4,5,7.
If this is hardcoded, then I can simply VM_a.var_1.ToString();
How can I achieve this? Is it System.Reflection ?
Problem 2 :
If I want to store in DB which VM that I should use for deserializing, how
can I do that from code?
Example :
I clicked a link to a form, and then get its type - let's say "Form A".
Then I looked into DB and know that for "Form A", I should deserialize it
using "VM_a".
However, since that information is retrieved as a String, how can I use it
on deserialization as a Type ?

No comments:

Post a Comment