How to read JSON file from folder project ASP.NET

Multi tool use
Multi tool use


How to read JSON file from folder project ASP.NET



I create a folder "js" inside Script folder and create a file json with array citys
and i try read this file on this folder and return a list to my select view.


{
"cidade": [
{ "Nome": "Curitiba" },
{ "Nome": "São Paulo" },
{ "Nome": "Rio de Janeiro" },
{ "Nome": "Santa Catarina" },
{ "Nome": "Rio Grande do Sul" },
{ "Nome": "Acre" },
{ "Nome": "Goias" }
]
}



My class:


public class Cidade {
public string Nome {
get;
set;
}
}

public class Cidades {
public IList < Cidade > cidades {
get;
set;
}
}



And my action :


public class Cidade {
public string Nome {
get;
set;
}
}

public class Cidades {
public IList < Cidade > cidades {
get;
set;
}
}



This is the error:
asp.net error





What is the problem?
– SLaks
Jul 1 at 18:18





Hi i add picture on post now, showing error
– Cezar Mdlosci
Jul 1 at 18:20





did you check if your json is being loaded correctly? it seems that is not....replace your json variable by the JSON that you have inside cidade.json. Probably it will works
– Elmer Dantas
Jul 1 at 18:23






Server.MapPath returns a path. You need to read the file.
– SLaks
Jul 1 at 18:28


Server.MapPath





my json var return: "C:\Users\username\source\repos\Exercicio 4\Exercicio 4\Scripts\js\cidade.json"
– Cezar Mdlosci
Jul 1 at 18:30





2 Answers
2



This code will have the json file path not the contents of json file:


var json = Server.MapPath("~/Scripts/js/cidade.json");



You should change it to following to read json contents:


var json = System.IO.ReadAllText(Server.MapPath("~/Scripts/js/cidade.json"));



You are also missing an s in your json data. Your class has a property IList<Cidade> cidades while your json has the key as cidad


s


IList<Cidade> cidades


cidad





this is not work , but thx
– Cezar Mdlosci
Jul 1 at 18:46





you also need to fix your json. Your Cidades is looking for cidades (with an s) while your json has the key cidade
– Neville Nazerane
Jul 1 at 18:51


Cidades


cidades


cidade





Thx , now work with your code
– Cezar Mdlosci
Jul 1 at 19:08



My final Code:


[HttpGet]
public ActionResult Get()
{
var json = System.IO.File.ReadAllText(Server.MapPath(@"~/App_Data/cidade.json"));
Cidade cidade = JsonConvert.DeserializeObject<Cidade>(json);
return View(cidade);

}



My class:


public class Cidades
{
public string Nome { get; set; }
}

public class Cidade
{
public List<Cidades> cidade { get; set; }
}






By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

lhl6hNy vgILN9AUPdI M4hqkdhwEdFYe55YU3,F,8v80hs91eCRcV69SvwMv xKaEhD,mT74PMccDvCTX1LB2Ml
523rq,lhRAYNdUpqsjgXGktIp9jX v9uYpwzgMIXWFSO,E,U

Popular posts from this blog

Rothschild family

Cinema of Italy