如何通过c#在json文件中写入数据? [英] How to write data in json file through c#?

查看:1193
本文介绍了如何通过c#在json文件中写入数据?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想调用json文件并在其上写一些数据,然后我必须将该json文件保存在C#中。请帮助我。



我尝试了什么:



我没有尝试任何东西。我没有发现任何好处与我的问题相关的教程。

I want to call json file and write some data on that and again i have to save that json file in C#.Please help me.

What I have tried:

I didnt tried any things.I didnt found any good tutorial related to my question.

推荐答案

尝试使用以下代码:



为类型创建自定义类数据序列化:

Try with below code:

Create a custom class for type of data serialization:
class employee
{
	public int id { get; set; }
	public string name { get; set; }
}



创建一个雇员对象并将其序列化以存储在.json文件中。添加引用 System.Web.Extensions 并使用命名空间 System.Web.Script.Serialization


Create an employee object and serialize it to store in .json file. Add reference System.Web.Extensions and use namespace System.Web.Script.Serialization :

employee eObj = new employee()
{
	id = 90,
	name = "manas"
};

string json = new JavaScriptSerializer().Serialize(eObj);

//write string to file
System.IO.File.WriteAllText(@"C:\path.json", json);


Json文件是纯文本。如果 File 类中的静态方法读取/写入数据,则可以使用。如果文件很大,您可以选择 Stream



请注意,使用这些方法,您需要确保您使用的是正确的JSON格式。



另外,

Json file is plain text. You can make use if static methods in File class read/write data to it. You may choose Stream if files are huge.

Note that with these methods, you will need to ensure that you are using correct JSON format.

Alternatively,
-> you can read the JSON, deserialize it into an object. 
-> Create more objects of same class or change data in existing object.
-> Serialize objects to json
-> Overwrite/append the file as per your need


这篇关于如何通过c#在json文件中写入数据?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆