Skip to content

Instantly share code, notes, and snippets.

@Taka414
Last active May 6, 2023 19:04
Show Gist options
  • Save Taka414/a5c4e2907e1fc842ada3ba21bc65f42d to your computer and use it in GitHub Desktop.
Save Taka414/a5c4e2907e1fc842ada3ba21bc65f42d to your computer and use it in GitHub Desktop.
public static class JsonUtility
{
/// <summary>
/// 任意のオブジェクトを JSON メッセージへシリアライズします。
/// </summary>
public static string Serialize(object graph)
{
using (var stream = new MemoryStream())
{
var serializer = new DataContractJsonSerializer(graph.GetType());
serializer.WriteObject(stream, graph);
return Encoding.UTF8.GetString(stream.ToArray());
}
}
/// <summary>
/// Jsonメッセージをオブジェクトへデシリアライズします。
/// </summary>
public static T Deserialize<T>(string message)
{
using (var stream = new MemoryStream(Encoding.UTF8.GetBytes(message)))
{
//var setting = new DataContractJsonSerializerSettings()
//{
// UseSimpleDictionaryFormat = true,
//};
var serializer = new DataContractJsonSerializer(typeof(T)/*, setting*/);
return (T)serializer.ReadObject(stream);
}
}
}
internal class Main
{
// データの作成
var p_1 = new Person()
{
ID = 0,
Name = "Taka",
};
p_1.Numbers = new int[] { 0, 1, 2, 3 };
p_1.NumberList.Add(0);
p_1.NumberList.Add(1);
p_1.NumberList.Add(2);
p_1.NumberList.Add(3);
p_1.Attributes.Add("key1", "value1");
p_1.Attributes.Add("key2", "value2");
p_1.Attributes.Add("key3", "value3");
var p_2 = new Person()
{
ID = 1,
Name = "PG",
};
p_2.Numbers = new int[] { 10, 11, 12, 13 };
p_2.NumberList.Add(10);
p_2.NumberList.Add(11);
p_2.NumberList.Add(12);
p_2.NumberList.Add(13);
p_2.Attributes.Add("keyAA", "valueAA");
p_2.Attributes.Add("keyBB", "valueBB");
p_2.Attributes.Add("keyCC", "valueCC");
// Personのリストを作成する
var pList = new List<Person>() { p_1, p_2 };
// リストをデシリアライズ
string json = JsonUtility.Serialize(pList);
// 内容をコンソールへ表示
Console.WriteLine(json);
// デシリアライズ
IList<Person> pDeserializedList = JsonUtility.Deserialize<IList<Person>>(body);
// 内容の出力
foreach (Person p in pDeserializedList)
{
Console.WriteLine("ID = " + p.ID);
Console.WriteLine("Name = " + p.Name);
foreach (KeyValuePair<string, string> att in p.Attributes)
{
Console.WriteLine(att.Key + " = " + att.Value);
}
}
}
// データ構造
[DataContract]
public class Person
{
[DataMember(Name = "id")]
public int ID { get; set; }
[DataMember(Name = "name")]
public string Name { get; set; }
// 配列
[DataMember(Name = "numbers")]
public int[] Numbers { get; set; }
// リスト型
[DataMember(Name = "list")]
public List<int> NumberList { get; private set; } = new List<int>();
// ハッシュマップ型
[DataMember(Name = "map")]
public IDictionary<string, string> Attributes { get; private set; } = new Dictionary<string, string>();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment