如何在C#应用程序中导入JsonConvert?

时间:2013-09-13 10:59:32

标签: c# json.net

我创建了一个C#库项目。该项目在一个类中有这一行:

JsonConvert.SerializeObject(objectList);

我收到错误说

  

当前上下文中不存在名称JsonConvert。

为了解决这个问题,我在引用中添加了System.ServiceModel.Web.dll,但没有运气。我该如何解决这个错误?

9 个答案:

答案 0 :(得分:146)

JsonConvert来自名称空间Newtonsoft.Json,而不是System.ServiceModel.Web

使用NuGet下载package

“项目” - > “管理NuGet包” - > “搜索”newtonsoft json“。 - >点击”安装“。

答案 1 :(得分:33)

右键点击该项目,然后选择Manage NuGet Packages.. 在那里选择Json.NET并安装

安装后,

使用以下命名空间

using Newtonsoft.Json;

然后使用以下内容反序列化

JsonConvert.DeserializeObject

答案 2 :(得分:15)

使用NuGet安装它:

Install-Package Newtonsoft.Json


发布this作为答案。

答案 3 :(得分:3)

工具 - > NuGet包管理器 - >包管理器控制台

PM> Install-Package Newtonsoft.Json

答案 4 :(得分:2)

或者,如果您使用的是dotnet Core,

添加到.csproj文件

  <ItemGroup>
    <PackageReference Include="Newtonsoft.Json" Version="9.0.1" />
  </ItemGroup>

并且

dotnet restore

答案 5 :(得分:2)

的Linux

If you're using Linux and .NET Core, see this question,您将要使用

dotnet add package Newtonsoft.Json

然后添加

using Newtonsoft.Json;

任何需要它的类。

答案 6 :(得分:1)

如果您开发.Net Core WebApi或WebSite,则无需安装newtownsoft.json 来执行json序列化/取消实现

只需确保您的控制器方法返回JsonResult并像此示例一样调用return Json(<objectoToSerialize>);

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

如果您正在开发 .Net Framework WebApi或WebSite,则需要使用NuGet下载并安装newtonsoft json

&#34;项目&#34; - &GT; &#34;管理NuGet包&#34; - &GT; &#34;搜索&#34; newtonsoft json&#34;。 - &GT;点击&#34;安装&#34;。

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

更多细节可以在这里找到 - https://docs.microsoft.com/en-us/aspnet/core/web-api/advanced/formatting?view=aspnetcore-2.1

答案 7 :(得分:0)

安装该软件包后,您需要通过运行以下命令将newtonsoft.json.dll添加到汇编路径中。

在使用我们的程序集之前,我们必须将其添加到全局程序集缓存(GAC)中。再次打开Visual Studio 2008命令提示符(对于Vista / Windows7 / etc。以管理员身份打开它)。并执行以下命令。 gacutil / i d:\ myMethodsForSSIS \ myMethodsForSSIS \ bin \ Release \ myMethodsForSSIS.dll

通过此链接获取更多信息 http://microsoft-ssis.blogspot.com/2011/05/referencing-custom-assembly-inside.html

答案 8 :(得分:0)

在C#中尝试一下。它的工作原理:

var jsonObject = JsonConvert.DeserializeObject(File.ReadAllText(MyFilePath));

导入以下名称空间:

对于JsonConvert:using Newtonsoft.Json;

对于文件:using System.IO;