Understanding how it works to convert an Object to Json

Asked

Viewed 48 times

1

I have a PUT route that receives a Json in the variable "edits" and from what I understand, in C# it ends up being an object.

I was researching a way to receive the file correctly and through some searches around, I found this code that I didn’t understand very well but it worked and it worked.

I really wanted to understand what is happening and why it was necessary to create a User type variable (my class)

Usuario _edicoes = Newtonsoft.Json.JsonConvert.DeserializeObject(edicoes);

1 answer

1


What happens in this case is that C# is a typed language and its JSON object is just a string until the serialization process occurs, that is, convert this JSON text to a typed C object#.

What the code:

Usuario _edicoes = Newtonsoft.Json.JsonConvert.DeserializeObject(edicoes);

Will do is the equivalent of creating a new object using the new:

Usuario _edicoes = new Usuario();

With the difference that the method DeserializeObject package Newtondoft.Json will map the properties of the JSON object to its class defined in C# (User), if they have the same name, example:

JSON user:

{
  "nome": "Fulano",
  "sobrenome": "da Silva",
  "email": "[email protected]"
}

User-class:

public class Usuario
{
   public string Nome { get; set; }
   public string Sobrenome { get; set; }
   public string Email { get; set; }
}

In this case, deserialization would normally occur, since the properties names of the two objects match. One detail is that the package Newtonsoft.Json already applies the name conventions and transforms the properties of Camel Case of the JSON to Pascal Case in the C#.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.