Treating JSON in C#

Asked

Viewed 395 times

1

I have a return of an HTTP request in JSON format. It comes as follows:

{
   "message": "authenticate"
}

It’s a simple return, but I’m a beginner in C# and would like to know how to assign only the string "authenticate" in a variable. Can someone help me?

  • This is the full json you get?

2 answers

1

You can use the class JsonConvert of Newtonsoft.JSON. The installation can be done directly by Visual Studio as a Nuget package. Just run the following in Package Manager:

Install-Package Newtonsoft.Json

To deserialize your JSON string in a practical and faster way, you can use a list of key and value pairs, do as:

var jsonString = GetJson();
var obj = JsonConvert.DeserializeObject<Dictionary<string, string>>(jsonString);

You can access the desired value in this way:

obj["message"];
// retorna a string "authenticate"

Another way is to do it in a more typed way, creating your JSON model in the form of a structured object, such as:

public class MeuTipo {
    public string message { get; set; }
}

So you can deserialize your JSON that way:

var jsonString = GetJson();
var obj = JsonConvert.DeserializeObject<MeuTipo>(jsonString);

And access like this:

obj.message;
// retorna a string "authenticate"

0

The Nuget Newtonsoft.JSON is a good solution for this type of situations.

You can create a class and deserializar the return:

Create a small example:

https://dotnetfiddle.net/ZYGhBn

Browser other questions tagged

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