Home > Software engineering >  Getting a build error when using Newtonsoft.Json in my Blazor app
Getting a build error when using Newtonsoft.Json in my Blazor app

Time:11-09

this is the code

@page "/"
@using Newtonsoft.Json
@using System.Text.Json
@using System.Text.Json.Serialization

<h1>Hello World</h1>

@code {

public class Account
{
    public string Email { get; set; }
    public bool Active { get; set; }
    public DateTime CreatedDate { get; set; }
    public IList<string> Roles { get; set; }
}

Account account = new Account
{
    Email = "[email protected]",
    Active = true,
    CreatedDate = new DateTime(2013, 1, 20, 0, 0, 0, DateTimeKind.Utc),
    Roles = new List<string>
    {
        "User",
        "Admin"
    }
};

string json = JsonConvert.SerializeObject(account, Formatting.Indented);

}

this is the error:

error CS0236: A field initializer cannot reference the non-static field, method, or property 'Index.account'

I am just learning Blazor. I am expecting the project to build.

CodePudding user response:

You should create a constructor (or antoher method) and put your code there.

@code {

    public class Account
    {
        public string Email { get; set; }
        public bool Active { get; set; }
        public DateTime CreatedDate { get; set; }
        public IList<string> Roles { get; set; }
    }

    public Index()
    {
        Account account = new Account
        {
            Email = "[email protected]",
            Active = true,
            CreatedDate = new DateTime(2013, 1, 20, 0, 0, 0, DateTimeKind.Utc),
            Roles = new List<string>
            {
                "User",
                "Admin"
            }
        };

        string json = JsonConvert.SerializeObject(account, Formatting.Indented);
    }

}

CodePudding user response:

IList is not serializable. Use List<T> instead.

  • Related