How to import JsonConvert in C# application?

后端 未结 9 1347
栀梦
栀梦 2020-12-03 02:33

I created a C# library project. The project has this line in one class:

JsonConvert.SerializeObject(objectList);

I\'m getting error saying

相关标签:
9条回答
  • 2020-12-03 03:03

    Install it using NuGet:

    Install-Package Newtonsoft.Json
    


    Posting this as an answer.

    0 讨论(0)
  • 2020-12-03 03:05

    After instaling the package you need to add the newtonsoft.json.dll into assemble path by runing the flowing command.

    Before we can use our assembly, we have to add it to the global assembly cache (GAC). Open the Visual Studio 2008 Command Prompt again (for Vista/Windows7/etc. open it as Administrator). And execute the following command. gacutil /i d:\myMethodsForSSIS\myMethodsForSSIS\bin\Release\myMethodsForSSIS.dll

    flow this link for more informATION http://microsoft-ssis.blogspot.com/2011/05/referencing-custom-assembly-inside.html

    0 讨论(0)
  • 2020-12-03 03:09

    If you are developing a .Net Core WebApi or WebSite you dont not need to install newtownsoft.json to perform json serialization/deserealization

    Just make sure that your controller method returns a JsonResult and call return Json(<objectoToSerialize>); like this example

    namespace WebApi.Controllers
    {
        [Produces("application/json")]
        [Route("api/Accounts")]
        public class AccountsController : Controller
        {
            // GET: api/Transaction
            [HttpGet]
            public JsonResult Get()
            {
                List<Account> lstAccounts;
    
                lstAccounts = AccountsFacade.GetAll();
    
                return Json(lstAccounts);
            }
        }
    }
    

    If you are developing a .Net Framework WebApi or WebSite you need to use NuGet to download and install the newtonsoft json package

    "Project" -> "Manage NuGet packages" -> "Search for "newtonsoft json". -> click "install".

    namespace WebApi.Controllers
    {
        [Produces("application/json")]
        [Route("api/Accounts")]
        public class AccountsController : Controller
        {
            // GET: api/Transaction
            [HttpGet]
            public JsonResult Get()
            {
                List<Account> lstAccounts;
    
                lstAccounts = AccountsFacade.GetAll();
    
                //This line is different !! 
                return new JsonConvert.SerializeObject(lstAccounts);
            }
        }
    }
    

    More details can be found here - https://docs.microsoft.com/en-us/aspnet/core/web-api/advanced/formatting?view=aspnetcore-2.1

    0 讨论(0)
提交回复
热议问题