How to read JSON file from folder project ASP.NET

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:
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.
What is the problem?
– SLaks
Jul 1 at 18:18