4
\$\begingroup\$

I'm writing a custom JavaScript converter to deserialize some JSON. Here's a few lines I'm writing:

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 = serializer.ConvertToType<int>(dictionary["NoteID"]);
      }
    }

How can this be improved?

\$\endgroup\$
0

3 Answers 3

7
\$\begingroup\$

you can do

TheObject.NoteID = NoteID;
\$\endgroup\$
3
\$\begingroup\$

It would be like this, you are already converting it to int with the tryParse

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;
      }
    }
}

or even shorter

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;
      }
    }
\$\endgroup\$
1
  • 1
    \$\begingroup\$ You might want to have noteID in out parameter instead of NoteID. Sorry couldn't edit it. \$\endgroup\$ Commented Jan 2, 2012 at 7:11
2
\$\begingroup\$

I would recommend the following...

public override object Deserialize(IDictionary<string, object> dictionary, Type type, JavaScriptSerializer serializer) 
  { 
    int noteID; 
    NotesModel TheObject = new NotesModel(); 

    object value;

    if (dictionary.TryGetValue("NoteID", out value)) 
    { 
      if (int.TryParse(serializer.ConvertToType<string>(value), out NoteID)) 
      { 
         TheObject.NoteID = noteId; 
      } 
    } 
}

This should cut your dictionary query by half.

\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.