32. C# da JSON faylini o'qish va uni C# ob'ektiga aylantirish uchun JsonReader dasturidan foydalaning.
Javob:
using System.IO;
using Newtonsoft.Json;
class Program
{
static void Main(string[] args)
{
// Read the JSON file into a string
string json = File.ReadAllText("inputfile.json");
// Deserialize the JSON string into a C# object
using (JsonReader reader = new JsonTextReader(new StringReader(json)))
{
JsonSerializer serializer = new JsonSerializer();
YourObject obj = serializer.Deserialize(reader);
}
// Do something with the object
// ...
}
}
Ushbu kod misolida biz avval "inputfile.json" faylining mazmunini json deb nomlangan o'zgaruvchiga o'qiymiz. Keyin JSON satrini JsonSerializerning Deserialize usuli yordamida YourObject deb nomlangan C# obyektiga aylantirish uchun JsonTextReader obyektidan foydalanamiz. kod>. Nihoyat, biz YourObject misolida kerakli amallarni bajarishimiz mumkin.
Koddagi "YourObject" ni "inputfile.json" faylingizdagi JSON tuzilishiga mos keladigan C# obyektining haqiqiy nomi bilan almashtirganingizga ishonch hosil qiling.
33. JsonWriter yordamida JSON fayliga ob'ekt yozish uchun C# usulini yozing.
Javob:
using (StreamWriter sw = new StreamWriter("outputfile.json"))
using (JsonWriter writer = new JsonTextWriter(sw))
{
JsonSerializer serializer = new JsonSerializer();
YourObject obj = new YourObject();
// Set any properties you need to on the object here...
obj.PropertyName = "Value";
// Serialize the object to JSON and write to the file
serializer.Serialize(writer, obj);
}
Ushbu kod misolida biz "outputfile.json" nomli yangi fayl yaratish uchun StreamWriter dan foydalanamiz. Keyin, biz StreamWriter misoliga yozuvchi JsonWriter obyektini yaratamiz. Keyinchalik, YourObject deb nomlangan C# obyektining namunasini yaratamiz va unga kerakli xususiyatlarni o'rnatamiz. Nihoyat, biz JsonSerializer ob'ektini JSONga seriallashtirish va JsonSerializer ning Serialize usuli yordamida JSON qatorini faylga yozish uchun foydalanamiz.
Do'stlaringiz bilan baham: |