Open棟梁Project - マイクロソフト系技術情報 Wiki

目次

概要

とある案件の要件で、

非構造化データを粘土細工のように
ゴリゴリと処理したいが、そういったことは、可能なのだろうか?

ということを調査した。

JSON.NET

ココが参考になる。

基本

シリアライズ・デシリアライズ

[JsonObject("aaa")]
public class AAA
{
  [JsonProperty("prop1")]
  public int property1 { get; set; }
  [JsonProperty("prop2")]
  public string property2  { get; set; }
}

既定値

応用

上記に

「階層構造を持ったJSONでも問題なくデシリアライズ可能。
JSON配列もListなどにパースしてくれる。」

とあるが、何処までやってくれるか?

・・・検証の結果、

型が特定できない構造のJSONの例

階層構造を持ったBean

配列(List<AAA>)

配列(Generic)も問題なく処理できる。

[JsonObject("aaa")]
public class AAA
{
  [JsonProperty("prop1")]
  public int property1 { get; set; }
  [JsonProperty("prop2")]
  [DefaultValue("hogehoge")]
  public string property2 { get; set; }
  [JsonProperty("prop3")]
  public AAA property3 { get; set; }
}
static void Main(string[] args)
{
 AAA aaa1 = new AAA();
 AAA aaa2 = new AAA();
 aaa1.property1 = 100;
 aaa1.property2 = "xxx";
 aaa2.property1 = 200;
 aaa2.property2 = "yyy";
 aaa1.property3 = aaa2;
 
 List<AAA> lstaaa = new List<AAA>();
 lstaaa.Add(aaa1);
 lstaaa.Add(aaa2);
 
 string json = JsonConvert.SerializeObject(lstaaa);
 Console.WriteLine(json);
 
 lstaaa = JsonConvert.DeserializeObject<List<AAA>>(json);

Primitive型とGeneric型

static void Main(string[] args)
{
  List<Dictionary<string, string>> parent = new List<Dictionary<string, string>>();
  Dictionary<string, string> child;

  child = new Dictionary<string, string>();
  child["aaa"] = "AAA";
  child["bbb"] = "BBB";
  child["ccc"] = "CCC";
  parent.Add(child);

  child = new Dictionary<string, string>();
  child["xxx"] = "XXX";
  child["yyy"] = "YYY";
  child["zzz"] = "ZZZ";
  parent.Add(child);

  string json = JsonConvert.SerializeObject(parent);
  Console.WriteLine(json);

  parent = JsonConvert.DeserializeObject<List<Dictionary<string, string>>>(json);

継承を使用

派生型をシリアライズできるが、問題は派生型にデシリアライズできないこと。

[JsonObject("aaa")]
public class AAA
{
  [JsonProperty("prop1")]
  public int property1 { get; set; }
  [JsonProperty("prop2")]
  [DefaultValue("hogehoge")]
  public string property2 { get; set; }
  [JsonProperty("prop3")]
  public AAA property3 { get; set; }
}

[JsonObject("bbb")]
public class BBB : AAA
{
  [JsonProperty("prop4")]
  public int property4 { get; set; }
}

[JsonObject("ccc")]
public class CCC : AAA
{
  [JsonProperty("prop4")]
  public string property4 { get; set; }
}
static void Main(string[] args)
{
  AAA aaa1 = new AAA();
  AAA aaa2 = new AAA();

  aaa1.property1 = 100;
  aaa1.property2 = "xxx";
  aaa1.property3 = new BBB();

  aaa2.property1 = 200;
  aaa2.property2 = "yyy";
  aaa2.property3 = new CCC();

  List<AAA> lstaaa = new List<AAA>();
  lstaaa.Add(aaa1);
  lstaaa.Add(aaa2);

  string json = JsonConvert.SerializeObject(lstaaa);
  Console.WriteLine(json);

  lstaaa = JsonConvert.DeserializeObject<List<AAA>>(json);

その他

型が特定できない構造のJSONをparseする例

参考

DataContractJsonSerializer?


トップ   新規 一覧 単語検索 最終更新   ヘルプ   最終更新のRSS