Harry Potter and the Sorcerer's Stone


C# da JSON faylini o'qish va uni C# ob'ektiga aylantirish uchun JsonReader dasturidan foydalaning


Download 192.49 Kb.
bet18/62
Sana17.06.2023
Hajmi192.49 Kb.
#1535967
1   ...   14   15   16   17   18   19   20   21   ...   62
Bog'liq
Algaritim amaliy-2

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.

Download 192.49 Kb.

Do'stlaringiz bilan baham:
1   ...   14   15   16   17   18   19   20   21   ...   62




Ma'lumotlar bazasi mualliflik huquqi bilan himoyalangan ©fayllar.org 2024
ma'muriyatiga murojaat qiling