Problem: Mit C# soll ein Objekt mit seinen Attributen in einer Datei im JSON Format abgespeichert werden. Es sollen keine third party libraries verwendet werden.
Eine ausführliche Erklärung des Quellcodes folgt in kürze, vorerst nur der reine Quellcode. Es handelt sich um ein Consolenprojekt.
using System;
using System.Collections.Generic;
using System.IO;
using System.Web.Script.Serialization;
// verweise die hinzugefügt werden müssen:
// - System.Runtime.Serialization
// - System.Web.Extensions
namespace ObjToJson
{
internal class JsonData
{
public List<String> letters;
public string hello;
public JsonData()
{
hello = "World!";
letters = new List<string> {"a", "b", "c", "d", "e", "f", "g", "h", "i",
"j", "k", "l", "m", "n", "o", "p", "q", "r",
"s", "t", "u", "v", "w", "x", "y", "z" };
}
}
public class Program
{
static void Main(string[] args)
{
JsonData appProp = new JsonData();
JsonData appPropRead = new JsonData();
// Aus dem Objekt in die Datei
var serial = new JavaScriptSerializer();
using (FileStream fs =
new FileStream(@"C:\tmp\serial\config.prop", FileMode.Create))
{
using (StreamWriter sw =
new StreamWriter(fs, System.Text.Encoding.UTF8))
{
string jser = serial.Serialize(appProp);
sw.Write(jser);
}
}
// Aus der Datei in das Objekt
using (FileStream fs =
new FileStream(@"C:\tmp\serial\config.prop", FileMode.Open))
{
using (StreamReader sr = new StreamReader(fs, System.Text.Encoding.UTF8))
{
sr.BaseStream.Position = 0;
string json = sr.ReadToEnd();
Console.WriteLine(json);
var serializer = new JavaScriptSerializer();
appPropRead = serializer
.Deserialize<JsonData>(json.TrimStart().TrimEnd());
Console.WriteLine("Hello " + appPropRead.hello);
}
}
Console.ReadKey();
}
}
}