Skip to main content
 首页 » 编程设计

c#之使用 Newtonsoft 序列化一个对象

2024年02月05日8cloudgamer

我正在尝试使用 Newtonsoft Json 转换器序列化一个对象,如下所示:

using System; 
using System.Collections.Generic; 
using System.IO; 
using System.Net; 
using Newtonsoft.Json; 
 
 string json = new Newtonsoft.Json.JsonConvert.SerializeObject(new 
            { 
                jlpt = "5" 
            }); 

但是它给了我一个错误的说法

SerializeObject does not exist.

但是,当我点击查看引用时,我看到了它。

谁能指出我做错了什么?

请您参考如下方法:

移除 Newtonsoft.Json.JsonConvert 的 new 实例创建,因为 SerializeObject 是静态方法,您不需要创建实例Newtonsoft.Json.JsonConvert 使用它

string json = Newtonsoft.Json.JsonConvert.SerializeObject(new 
            { 
                jlpt = "5" 
            }); 

另外,如果您将 using Newtonsoft.Json; 添加到程序中,那么您只需像这样使用

string json = JsonConvert.SerializeObject(new 
            { 
                jlpt = "5" 
            });