patterncsharpMinor
Converter for deserializing JSON
Viewed 0 times
jsondeserializingforconverter
Problem
I'm writing a custom JavaScript converter to deserialize some JSON. Here's a few lines I'm writing:
How can this be improved?
public override object Deserialize(IDictionary dictionary, Type type,
JavaScriptSerializer serializer)
{
int NoteID;
NotesModel TheObject = new NotesModel();
if (dictionary.ContainsKey("NoteID"))
{
if (int.TryParse(serializer.ConvertToType(dictionary["NoteID"]),
out NoteID))
{
TheObject.NoteID = serializer.ConvertToType(dictionary["NoteID"]);
}
}How can this be improved?
Solution
It would be like this, you are already converting it to int with the tryParse
or even shorter
public override object Deserialize(IDictionary dictionary, Type type, JavaScriptSerializer serializer)
{
int noteID;
NotesModel TheObject = new NotesModel();
if (dictionary.ContainsKey("NoteID"))
{
if (int.TryParse(serializer.ConvertToType(dictionary["NoteID"]), out noteID))
{
TheObject.NoteID = noteId;
}
}
}or even shorter
public override object Deserialize(IDictionary dictionary, Type type, JavaScriptSerializer serializer)
{
int noteID;
NotesModel TheObject = new NotesModel();
if (dictionary.ContainsKey("NoteID") && int.TryParse(serializer.ConvertToType(dictionary["NoteID"]), out NoteID))
{
TheObject.NoteID = noteId;
}
}Code Snippets
public override object Deserialize(IDictionary<string, object> dictionary, Type type, JavaScriptSerializer serializer)
{
int noteID;
NotesModel TheObject = new NotesModel();
if (dictionary.ContainsKey("NoteID"))
{
if (int.TryParse(serializer.ConvertToType<string>(dictionary["NoteID"]), out noteID))
{
TheObject.NoteID = noteId;
}
}
}public override object Deserialize(IDictionary<string, object> dictionary, Type type, JavaScriptSerializer serializer)
{
int noteID;
NotesModel TheObject = new NotesModel();
if (dictionary.ContainsKey("NoteID") && int.TryParse(serializer.ConvertToType<string>(dictionary["NoteID"]), out NoteID))
{
TheObject.NoteID = noteId;
}
}Context
StackExchange Code Review Q#6887, answer score: 3
Revisions (0)
No revisions yet.