将对象转换为 JSON C#

WBOY
发布: 2024-09-03 15:27:30
原创
234 人浏览过

必须获取对象的当前状态才能存储它或稍后检索它,编码时应考虑这一点,添加自定义代码来输出对象的状态,这在C#中称为将对象转换为Json字符串必须根据我们对对象类型的了解类型,对对象的每个属性进行编码。当对象类型的定义发生变化时,必须更改代码,并且我们利用 Newtonsoft 的 Json.NET 库将对象转换为 C# 中的 Json,它使用代码为我们提供了对象字符串的完整表示用单行写的。

语法:

Variable variable_name =Newtonsoft.Json.JsonConvert.SerializeObject(parameter);
登录后复制

C# 中对象到 JSON 字符串的转换

  • 让我们看看如何使用 NewtonsoftJson 完成对象的序列化,只不过是在 C# 中将对象转换为 Json 字符串。
  • 创建一个新的 Visual Studio 项目,作为将对象转换为 Json 字符串的第一步。
  • NewtonsoftJson 使用 Nuget 安装。
  • 创建一个示例类来序列化,只不过将对象转换为 Json 字符串。
  • 然后创建方法将对象转换为 Json 字符串或在 C# 中序列化对象。
  • 最后执行程序将C#中的对象序列化,无非就是将C#中的对象转换为Json字符串。

将对象转换为 JSON C# 的示例

下面给出了提到的示例:

示例#1

C# 程序,演示对象到 Json 字符串的转换,这只不过是 C# 中对象的序列化。

代码:

using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.IO;
//a namespace called Serial is defined
namespace Serial
{
//a class called Data is defined
public class Data
{
//a string variable is defined which can be set or retrieved using get or set method
public string Name1 { get; set; }
//a list is defined which can be set or retrieved using get or set method
public List<int> Ids { get; set; }
//a method called Print is defined in which the name and the list is printed
public void Print()
{
Console.WriteLine("The Name is: " + Name1);
Console.WriteLine("The Identifiers used are: " + string.Join<int>(",", Ids));
Console.WriteLine();
Console.WriteLine();
}
}
//a class called check is defined
public class Check
{
//a file path is defined and stored in a string variable
const string fPath = @"d:\ex.txt";
//Serialize method is defined in which instances of Json writer and Stream writer classes are defined to write into the file
public static void Serialize(object ob)
{
varserialise = new JsonSerializer();
using (var ns = new StreamWriter(fPath))
using (JsonWriter writer1 = new JsonTextWriter(ns))
{
serialise.Serialize(writer1, ob);
}
}
//Deserialize method is defined in which instances of Json text reader and Stream reader classes are defined to read from the file
public static object Deserialize(string pa)
{
varserialise = new JsonSerializer();
using (var ns = new StreamReader(pa))
using (var reader1 = new JsonTextReader(ns))
{
return serialise.Deserialize(reader1);
}
}
//main method is called
public static void Main(string[] args)
{
vardat = new Data
{
Name1 = "ShobhaShivakumar",
Ids = new List<int>{ 10, 20, 30, 40 }
};
Console.WriteLine("Before serialization of the objects, the list of the objects are:");
Console.WriteLine("-------------------------------------------------------------------");
Console.WriteLine();
dat.Print();
Serialize(dat);
vardeserialise = Deserialize(fPath);
Console.WriteLine("After de-serialization of the object, the objects are:");
Console.WriteLine("---------------------------");
Console.WriteLine();
Console.WriteLine(deserialise);
}
}
}
登录后复制

输出:

将对象转换为 JSON C#

说明:

  • 在上面的程序中,定义了一个名为 Serial 的命名空间。然后定义一个名为Data的类。然后定义一个字符串变量,可以使用 get 或 set 方法设置或检索该变量。然后定义一个列表,可以使用 get 或 set 方法设置或检索该列表。然后定义一个名为 Print 的方法,在其中打印名称和列表。然后定义一个名为check的类。然后定义文件路径并将其存储在字符串变量中。
  • 然后定义了 Serialize 方法,其中定义了 Jsonwriter 和 Streamwriter 类的实例来写入文件。然后定义 De serialize 方法,其中定义 Jsontext reader 和 Streamreader 类的实例来从文件中读取。然后调用 main 方法,该方法调用该方法来显示对象序列化之前的输出。

示例#2

C# 程序来演示程序中手动序列化和 Json 序列化的区别。

代码:

using System;
using System.Text;
using System.Collections.Generic;
//a class called check is defined
public class Check
{
//main method is called
public static void Main()
{
//an instance of the Create request1 class and string builder class is created
var request = CreateRequest1();
var output1 = new StringBuilder();
//Since we are using manual serialization here, we have to output the properties manually
output1.AppendFormat("The unique ID is: {0}\n", request.UniqueID);
output1.AppendFormat("The unique Name is: {0}\n", request.UniqueName);
output1.AppendFormat("The unique Surname is: {0}\n", request.UniqueSurname);
output1.AppendFormat("The Last Sign In is: {0}\n", request.UniqueLastSignIn);
//We need to make use of for loop to output the nested attributes in case of manual serialization
output1.AppendFormat("The Attributes are:\n");
foreach (varsh in request.UniqueAttributes)
{
output1.AppendFormat("    {0}\n", sh);
}
Console.WriteLine(output1.ToString());
Console.WriteLine(Newtonsoft.Json.JsonConvert.SerializeObject(request);
//We are using Json serialization to improve the readability
Console.WriteLine(Newtonsoft.Json.JsonConvert.SerializeObject(request, Newtonsoft.Json.Formatting.Indented));
}
//a method called Create request1 is defined
public static Req CreateRequest1()
{
return new Req
{
UniqueID = 10,
UniqueName = "Shobha",
UniqueSurname = "Shivakumar",
UniqueLastSignIn = DateTime.Now,
UniqueAttributes = new List<string>
{
"Beautiful",
"Tall",
"Intelligent",
"Wise",
}
};
}
//a class called req is created
public class Req
{
public intUniqueID {get;set;}
public string UniqueName {get;set;}
public string UniqueSurname {get;set;}
public DateTimeUniqueLastSignIn {get;set;}
public List<string>UniqueAttributes {get;set;}
}
}
登录后复制

输出:

将对象转换为 JSON C#

说明:

  • 在上面的程序中,定义了一个名为check的类。然后调用main方法。然后创建 Create request1 类和字符串生成器类的实例。然后,由于我们在这里使用手动序列化,因此我们必须手动输出属性。然后我们需要利用for循环来输出嵌套的属性,因为这是手动序列化的情况。
  • 然后我们使用Json序列化来提高可读性。然后定义了一个名为 Create request1 的方法。然后创建一个名为 req 的类,其中使用 get 或 set 方法设置和检索所有属性。

以上是将对象转换为 JSON C#的详细内容。更多信息请关注PHP中文网其他相关文章!

相关标签:
来源:php
本站声明
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责声明 Sitemap
PHP中文网:公益在线PHP培训,帮助PHP学习者快速成长!