[英]How to convert json data to object in C#?
When I convert the json file data to object I get the exception below. 当我将json文件数据转换为对象时,我得到以下异常。 How do I resolve?
我该如何解决?
Unhandled Exception: Newtonsoft.Json.JsonSerializationException: Cannot deserialize the current JSON array (eg [1,2,3]) into type 'ChattingApp.API.Models.User' because the type requires a JSON object (eg {"name":"value"}) to deserialize correctly.
未处理的异常:Newtonsoft.Json.JsonSerializationException:无法将当前JSON数组(例如[1,2,3])反序列化为类型'ChattingApp.API.Models.User',因为该类型需要JSON对象(例如{“name”: “value”})正确反序列化。
Here is my Code... 这是我的代码......
using System.Collections.Generic;
using ChattingApp.API.Models;
namespace ChattingApp.API.Data
{
public class Seed
{
private readonly DataContext _context;
public Seed(DataContext context)
{
_context = context;
}
public void SeedUsers()
{
var userData = System.IO.File.ReadAllText("Data/UserSeedData.json");
var users = Newtonsoft.Json.JsonConvert.DeserializeObject<List<User>>(userData);
foreach (var user in users)
{
byte[] passwordHash, passwordSalt;
CreatePasswordHash("password", out passwordHash, out passwordSalt);
user.PasswordHash = passwordHash;
user.PasswordSalt = passwordSalt;
user.Username = user.Username.ToLower();
_context.Users.Add(user);
}
_context.SaveChanges();
}
private void CreatePasswordHash(string password, out byte[] passwordHash, out byte[] passwordSalt)
{
using(var hmac =new System.Security.Cryptography.HMACSHA512())
{
passwordSalt=hmac.Key;
passwordHash=hmac.ComputeHash(System.Text.Encoding.UTF8.GetBytes(password));
}
}
}
}
It appears that the JSON within the .json file is invalid. 看来.json文件中的JSON无效。 Given that you are expecting a list of 'Users' to be returned I would expect the JSON to be formatted like this :
鉴于您期望返回“用户”列表,我希望JSON的格式如下:
[
{"Username": "Cooper",
"Gender": "male",
"DateOfBirth": "1980-01-21",
"Password": "password",
"KnownAs": "Cooper",
"Created": "2017-04-15"},
{"Username": "Blyth",
"Gender": "male",
"DateOfBirth": "1986-06-10",
"Password": "password213",
"KnownAs": "SomeDude",
"Created": "2016-02-08"}
]
You can also use https://jsonlint.com/ to validate your json. 您还可以使用https://jsonlint.com/验证您的json。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.