如何解析 JSON 文件

huangapple go评论54阅读模式
英文:

How to parse json file

问题

我在解析中遇到了问题

我的 JSON 文件:

[{
    "username": "abc",
    "number": "1",
    "Coordinates": "3479087.7179635554,4723293.992024612,3587934.046241646,4936094.678770542"
 },
 {
    "username": "ab",
    "number": "2",
    "Coordinates": "3638076.736796722,4693942.173163104,3669874.540563355,4955662.558011548"
}]

模型:

namespace WebUygAPI.Models
{
    public class DrawInfo
    {
        public string username { get; set; } 
        public string number { get; set; }
        public string coordinates { get; set; }
    }
}

我在控制器中遇到的问题是:

[HttpGet]
[Route("GetDraws")]
public async Task<IActionResult> get()
{
    string filePath = @"C:\Users\Casper\source\repos\WebUygAPI\WebUygAPI\LineData.json";
    using (StreamReader file = new StreamReader(filePath))
    {
        string o1 = file.ReadToEnd();
    }
    return Ok();
}

当我进行调试时,我可以看到 o1 中的 JSON 文件,但我无法解析它。

我尝试进行解析,但出现了错误,例如

newtonsoft.json.jsonreaderexception: 在解析值时遇到意外字符

英文:

I have a problem with parsing

my json file:

[{
    &quot;username&quot;: &quot;abc&quot;,
    &quot;number&quot;: &quot;1&quot;,
    &quot;Coordinates&quot;: &quot;3479087.7179635554,4723293.992024612,3587934.046241646,4936094.678770542&quot;
 },
 {
    &quot;username&quot;: &quot;ab&quot;,
    &quot;number&quot;: &quot;2&quot;,
    &quot;Coordinates&quot;: &quot;3638076.736796722,4693942.173163104,3669874.540563355,4955662.558011548&quot;
}]

modal:

namespace WebUygAPI.Models
{
    public class DrawInfo
    {
        public string username { get; set; } 
        public string number { get; set; }
        public string coordinates { get; set; }
    }
}

The problem I'm having in the controller is:

[HttpGet]
[Route(&quot;GetDraws&quot;)]
public async Task&lt;IActionResult&gt; get()
{
	string filePath = @&quot;C:\Users\Casper\source\repos\WebUygAPI\WebUygAPI\LineData.json&quot;;
	using (StreamReader file = new StreamReader(filePath))
	{
		string o1 = file.ReadToEnd();
	}
	return Ok();
}

When I'm debugging I can see json file in o1 but I couldn't parse it.

I tried to parse but I had errors such as

> newtonsoft.json.jsonreaderexception: unexpected character encountered while parsing value

答案1

得分: -1

我建议使用这段代码:

使用 Newtonsoft.Json;

var json = File.ReadAllText(filePath);

List<DrawInfo> info = JsonConvert.DeserializeObject<List<DrawInfo>>(json);
英文:

I recommend this code

using Newtonsoft.Json;

 var json = File.ReadAllText(filePath);

List&lt;DrawInfo&gt; info = JsonConvert.DeserializeObject&lt;List&lt;DrawInfo&gt;&gt;(json);

</details>



huangapple
  • 本文由 发表于 2023年2月14日 21:50:29
  • 转载请务必保留本文链接:https://go.coder-hub.com/75448800.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定