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\$

migrated from stackoverflow.com Dec 15 '11 at 21:08

This question came from our site for professional and enthusiast programmers.

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
    \$\begingroup\$ You might want to have noteID in out parameter instead of NoteID. Sorry couldn't edit it. \$\endgroup\$ – Nilesh Thakkar Jan 2 '12 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, privacy policy and cookie policy