First, I recommend that you use a well-defined text / file structure to save your information, such as JSON. This will make the processing of your data simpler and more convenient to manipulate.
JSON is basically a lightweight information / data exchange format between systems and means JavaScript Object Notation. Do not be alarmed by "JavaScript" as it is not only with Javascript that we can use this type of file. I recommend you read a little more about the subject and understand how this type of file works and its structure.
Recommended reading : What is JSON?
Transforming your file into JSON
Replace the contents of your User: (name = Peter, age = 25) by:
{
"Nome" : "Pedro",
"Idade" : "25"
}
You can save the file in .json
format instead of .txt
and send it to Pastebin . That done, we can go to the code part.
Installing the library that will handle your JSON file
In Visual Studio (I believe you are using it to encode in C #), within your project, right-click References
and then select the Manage NuGet Packages
:
Onceyouhavedonethis,selectBrowse
,inthetextboxtype"json", select the item Newtonsoft.Json
and then click install:
CreatingthetemplateclassforyourJSONfile
Withinyourproject,addaclassthatwillbeusedasatemplateforyourJSONfile.Givenyourquestion,we'retalkingaboutauser,socreateaclasscalledUsuario
thathasthefollowingstructure:
publicclassUsuario{publicstringNome{get;set;}publicstringIdade{get;set;}}
NotethatthenameoftheclasspropertiesareexactlythesameasthenamesthatareinthestructureofyourJSON.InthisfirstmomentanduntilyoubecomefamiliarwithJSON,wehavetokeepitthatway.
ManipulatingYourJSONFile
Nowthatwehaveourenvironmentready,wecanbegintomanipulatethedatafromourJSONfile.
Inthesameclassthatputthecodeinthequestion,putthefollowingusing
directiveatthetopofyourclass:
usingNewtonsoft.Json;
Now,downloadyourfileandmakeitanobjectoftypeUsuario
,whichwasthemodelclasswecreatedearlier:
WebClientweb=newWebClient();stringresult=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 to use as an example. Remember to change the link to your file link.
When you run the code above, you will notice that the content of your JSON file that was in Pastbin was transformed into an object of type Usuario
which in the above code I called usuario
. With this, we can access the object and check its Nome
and Idade
properties, which will contain exactly what is in your JSON file:
Finally,putthecontentoftheobjectusuario
,intothedesiredvariables:
stringnome=usuario.Nome;stringidade=usuario.Idade;
Andifyouwanttoaddmoreusers?
FromthetemplateIexplained,only1userperfilewouldbeallowed(Ihopedyourquestionwouldcomeupsothatyoucouldconcludethequestiondefinitively).Nowlet'smakethemodificationssothatyoucanfindmoreusersofthefile.
Ihavealreadycreatedaverynicestructureforyourfile,let'skeepitandmodifyonlyourcode.
Givenitsstructure,thefilehasaUsers
objectthatisalistofusers,thatis,alistofourclassUsuario
previouslycreated.
Let'snowcreateanotherclass,calledArquivo
,whichwillserveasthenewJSONfiletemplate:
publicclassArquivo{publicList<Usuario>Users{get;set;}}
NotethatthisnewclasshastheUsers
property,whichisexactlythesameasthenameyougavetoyourlistofusersinyourJSONfile.AlsonotethatthepropertyisaUsuario
list.RemembertousetheusingSystem.Collections.Generic
directivetoaccessList
.
Onceyou'vedonethis,modifyyourcodesnippetthatdoestheJSONfilemanipulationtolooklikethis:
WebClientweb=newWebClient();stringresult=web.DownloadString("https://pastebin.com/raw/j0P175Wq");
Arquivo arquivo = JsonConvert.DeserializeObject<Arquivo>(result);
List<Usuario> usuarios = arquivo.Users;
Here, notice that it is no longer the class Usuario
that serves as the template for the JSON file, but the class Arquivo
through the line JsonConvert.DeserializeObject<Arquivo>
.
When executing the above code, you will notice that the user list is inside the arquivo
object and within the Users
property.