Skip to content

Instantly share code, notes, and snippets.

@lavn0
Last active October 22, 2016 03:32
Show Gist options
  • Select an option

  • Save lavn0/bc567abd3b46e93a2442ba73b1f49d3e to your computer and use it in GitHub Desktop.

Select an option

Save lavn0/bc567abd3b46e93a2442ba73b1f49d3e to your computer and use it in GitHub Desktop.
.NET 標準の処理でオブジェクトを json に変換及び逆変換する処理の実装
// add reference to System.Runtime.Serialization, Version=4.0.0.0
using System.IO;
using System.Runtime.Serialization.Json;
using System.Text;
/// <summary>json形式のファイルまたは文字列をインスタンスに変換またはその逆変換を行います。
/// 変換に用いるインスタンスには<see cref="System.Runtime.Serialization.DataContract"/> 属性が必要です。</summary>
public static class JsonParser
{
public static T ReadObject<T>(Stream stream)
{
return (T)new DataContractJsonSerializer(typeof(T)).ReadObject(stream);
}
public static T ReadObject<T>(string fileName)
{
var str = File.ReadAllText(fileName);
using (var ms = new MemoryStream(Encoding.UTF8.GetBytes(str)))
{
return ReadObject<T>(ms);
}
}
public static void WriteObject<T>(T obj, Stream stream)
{
new DataContractJsonSerializer(typeof(T)).WriteObject(stream, obj);
}
public static void WriteObject<T>(T obj, string fileName)
{
using (var sw = new StreamWriter(fileName))
{
WriteObject<T>(obj, sw.BaseStream);
}
}
public static T ParseObject<T>(string jsonString)
{
using (var ms = new MemoryStream(Encoding.UTF8.GetBytes(jsonString)))
{
return ReadObject<T>(ms);
}
}
public static string ParseObject<T>(T obj)
{
MemoryStream ms = null;
try
{
ms = new MemoryStream();
WriteObject<T>(obj, ms);
ms.Seek(0, SeekOrigin.Begin);
using (var sr = new StreamReader(ms))
{
ms = null;
return sr.ReadToEnd();
}
}
finally
{
ms?.Dispose();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment