如何在C#中将JSON数据转换为对象?

时间:2019-05-21 13:37:50

标签: c# json .net-core

当我将json文件数据转换为对象时,出现以下异常。我该如何解决?

  

未处理的异常:Newtonsoft.Json.JsonSerializationException:无法将当前JSON数组(例如[1,2,3])反序列化为类型“ ChattingApp.API.Models.User”,因为该类型需要JSON对象(例如{ name“:” value“})以正确反序列化。

这是我的代码...

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));

            }

        }
    }
}

1 个答案:

答案 0 :(得分:0)

.json文件中的JSON无效。 鉴于您期望返回“用户”列表,所以我希望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"}
]

您还可以使用https://jsonlint.com/来验证json。