csharp to json code example
Example 1: c# serialize json
using System.Text.Json;
var jsonString = JsonSerializer.Serialize(yourObject);
var obj = JsonSerializer.Deserialize<YourObject>(stringValue);
Example 2: object to json c#
using Newtonsoft.Json;
var jsonString = JsonConvert.SerializeObject(obj);
Example 3: c# JsonIO
namespace JsonHelper
{
public static class JsonIO
{
private static object mutex = new object();
public static Dictionary<string,object> LockList = new Dictionary<string,object>();
public static T CastJsonToObject<T>(this string jsonstr) where T : new()
{
try
{
return JsonConvert.DeserializeObject<T>(jsonstr);
}
catch(Exception ex)
{
return new T();
}
}
private static object GetLock(string text)
{
lock(mutex)
{
if (!LockList.ContainsKey(text))
{
LockList[text] = new object();
}
foreach (string key in LockList.Keys.ToList<string>())
{
if (!key.Equals(text) && !Monitor.IsEntered(LockList[key]))
{
LockList.Remove(key);
}
}
}
return LockList[text];
}
public static T Load<T>(string path) where T:new()
{
if (File.Exists(path))
{
string fullpath = Path.GetFullPath(path);
lock(GetLock(fullpath))
{
using (FileStream fs = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.Read))
{
using (StreamReader sr = new StreamReader(fs))
{
string s = sr.ReadToEnd();
fs.Close();
try
{
return JsonConvert.DeserializeObject<T>(s);
}
catch
{
JsonIO.Save(path, new T());
return new T();
}
}
}
}
}
else
{
JsonIO.Save(path, new T());
return new T();
}
}
public static void SetDefaultSerializer()
{
JsonConvert.DefaultSettings = (() =>
{
var settings = new JsonSerializerSettings();
settings.Converters.Add(new StringEnumConverter { });
return settings;
});
}
public static void Save(string path, object cfg)
{
string fullpath = Path.GetFullPath(path);
lock (GetLock(fullpath))
{
AutoResetEvent autoResetEvent = new AutoResetEvent(false);
DirHelper.CreateDirectory(path);
try
{
using (FileStream fs = new FileStream(path, FileMode.Create, FileAccess.ReadWrite, FileShare.Read))
{
using (StreamWriter sw = new StreamWriter(fs))
{
sw.Write(JsonConvert.SerializeObject(cfg, Formatting.Indented));
}
fs.Close();
}
}
catch (Exception ex)
{
var fileSystemWatcher =
new FileSystemWatcher(Path.GetDirectoryName(path))
{
EnableRaisingEvents = true
};
fileSystemWatcher.Changed +=
(o, e) =>
{
if (Path.GetFullPath(e.FullPath) == Path.GetFullPath(path))
{
try
{
using (FileStream fs = new FileStream(path, FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.Read))
{
using (StreamWriter sw = new StreamWriter(fs))
{
sw.Write(JsonConvert.SerializeObject(cfg, Formatting.Indented));
}
fs.Close();
}
}
catch (Exception ex2)
{
}
autoResetEvent.Set();
}
};
autoResetEvent.WaitOne();
}
}
}
}
}
Example 4: json to csharp
public static T Deserialize(string serializedData)
{
var deJson = JsonConvert.DeserializeObject<T>(serializedData);
return deJson;
}
public static string Serialize(object objectName)
{
var settings = new JsonSerializerSettings()
{
ContractResolver = new OrderedContractResolver()
};
var json = JsonConvert.SerializeObject(objectName, Formatting.Indented, settings);
return json;
}
public static string Serialize(object objectName)
{
var json = JsonConvert.SerializeObject(objectName, Formatting.Indented);
return json;
}