Treating JSON in C #

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 new to C # and would like to know how to assign only the "authenticate" string to a variable. Can anyone help me?

    
asked by anonymous 14.10.2017 / 15:53

2 answers

0

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

You can create a class and deserialize the return:

Create a small example:

link

    
14.10.2017 / 19:03
0

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

Install-Package Newtonsoft.Json

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

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

You can access the desired value this way:

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

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

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

So you can deserialize your JSON like this:

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

And access it like this:

obj.message;
// retorna a string "authenticate"
17.10.2017 / 00:31