Fetch content from an online file

Asked

Viewed 94 times

0

string nome, idade, valores;

WebClient WEBC = new WebClient();

public void Exemplo()
{
    valores = WEBC.DownloadString("https://pastebin.com/raw/r4GjhKQ3");
}

I want to take the values of the name and age after the '=' of the variable 'values' (https://pastebin.com/raw/r4GjhKQ3) and then I want to save those values in the variables I declared up there (name and age).

EDIT

What if I need to add more users? For example:

{
    "Users":[{"Nome":"Pedro","Idade":"25"},{"Nome":"Lucas","Idade":"19"}]
}
  • This Pastebin text exists by default or specific mark-up language?

  • has the possibility to transform into json as shown by Perozzo or necessarily needs to be in the format in which it is ?

1 answer

3


First, I recommend using a well-defined text/file structure to save your information, such as JSON. This will make the handling of your data simpler and more practical to handle.

JSON is basically a lightweight format for exchanging information/data across systems and stands for Javascript Object Notation. Do not be alarmed by "Javascript", because it is not only with Javascript that we can use this type of file. I recommend that you read a little more on the subject and understand how this type of file works and its structure.

Recommended reading: What is JSON?

Turning your file into JSON

Replace the contents of your file User:(name=Peter, age=25) for:

{
    "Nome" : "Pedro",
    "Idade" : "25"
}

You can save the file with the format .json instead of .txt and send to the Pastebin. Once that’s done, we can go to the code part.

Installing the library that will manipulate your JSON file

In Visual Studio (I believe you’re using it to encode in C#), inside your project, right-click on References and then select the option Manage NuGet Packages:

inserir a descrição da imagem aqui

Once done, select Browse, in the text box type "json", select the item Newtonsoft.Json and then click install:

inserir a descrição da imagem aqui

Creating the template class for your JSON file

Within your project, add a class that will be used as a template for your JSON file. Given your question, we’re talking about a user, so create a class called Usuario which has the following structure:

public class Usuario
{
    public string Nome { get; set; }
    public string Idade { get; set; }
}

Note that the name of class properties are exactly same as the names that are in the structure of your JSON. At this first moment and until you become familiar with JSON, we have to keep this way.

Manipulating your JSON file

Now that we have our environment ready, we can start manipulating the data from our JSON file.

In the same class that put the code in the question, put the following directive using at the top of his class:

using Newtonsoft.Json;

Now, download your file and turn it into an object of the type Usuario, which was the model class we created earlier:

WebClient web = new WebClient();

string result = web.DownloadString("https://pastebin.com/raw/j0P175Wq");

Usuario usuario = JsonConvert.DeserializeObject<Usuario>(result);

The link I used is from a file I put in Pastebin for example. Remember to change the link to your file link.

When running the above code, you will notice that the contents of your JSON file were in the Pastbin has been converted to an object of the type Usuario that in the code above I called usuario. With this, we were able to access the object and verify its properties Nome and Idade, which will contain exactly what is in your JSON file:

inserir a descrição da imagem aqui

To finish, place the contents of the object usuario, on the desired variables:

string nome = usuario.Nome;
string idade = usuario.Idade;

And if you want to add more users?

Of the model I explained, only 1 user per file would be allowed (I waited for your question to come up so you could finish the question). Now let’s go through the modifications so that it is possible to fetch more users from the file.

I saw that already created a very nice structure for your file, we will keep it and modify only our code.

Given its structure, the file has an object Users which is a list of users, that is, a list of our class Usuario previously created.

We will now create another class, called Arquivo, which will serve as the new template of the JSON file:

public class Arquivo
{
    public List<Usuario> Users { get; set; }
}

Note that this new class has the property Users, which is exactly the same as the name you gave to your list of users in your JSON file. Also note that the property is a list of Usuario. Remember to use the directive using System.Collections.Generic to gain access to List.

Once done, modify your code snippet that handles the JSON file to look like this:

WebClient web = new WebClient();

string result = web.DownloadString("https://pastebin.com/raw/j0P175Wq");

Arquivo arquivo = JsonConvert.DeserializeObject<Arquivo>(result);

List<Usuario> usuarios = arquivo.Users;

Here, realize that it is no longer the class Usuario which serves as a template for the JSON file, and yes the class Arquivo across the line JsonConvert.DeserializeObject<Arquivo>.

When executing the above code, you will notice that the user list is inside the object arquivo and within the property Users.

  • 1

    Thanks a lot! I didn’t know this method.

Browser other questions tagged

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