2017年9月6日水曜日

C#でJSONを出力する

C#でJSONを出力する必要に迫られたのでメモ。

まずは、出力するJSONを定義します。
サンプルとしてはこんなのを作ります。

{
"title": "Harry Potter and the Philosopher's Stone",
"author": "J.K. Rowling",
"hoge": {
"stringField": "piyo",
"numField": 123,
"floatField": 20.315,
"boolField": false,
"huga": {
"piyo": ["orange","apple"]
}
},
"tags": ["novel","story","magic"],
"valiableTags": [123,false,"str"],
"intArray": [1,2,3,4,5],
"floatArray": [1.2,1.3,1.4,2.0],
"date": "2016/11/29T12:34:56.000",
"year": "1997"
}
view raw sample.json hosted with ❤ by GitHub
まずは、JSONをC#のクラスに変換します。
VSでもできるようですが、json2csharpをつかいます。


作成されたクラスを少々手直しして、クラスとして追加します。

using System.Collections.Generic;
namespace json_sample
{
namespace JsonNodeHoge
{
public class Huga
{
public List<string> piyo { get; set; }
}
}
public class Hoge
{
public string stringField { get; set; }
public int numField { get; set; }
public double floatField { get; set; }
public bool boolField { get; set; }
public JsonNodeHoge.Huga huga { get; set; }
}
public class RootObject
{
public string title { get; set; }
public string author { get; set; }
public Hoge hoge { get; set; }
public List<string> tags { get; set; }
public List<object> valiableTags { get; set; }
public List<int> intArray { get; set; }
public List<double> floatArray { get; set; }
public string date { get; set; }
public string year { get; set; }
}
}
view raw json_sample.cs hosted with ❤ by GitHub
これをつかってJSONを作成します。
ここでは、Json.NETをつかいます。
こんな感じで組み立てていきます。

//ルートノード
var root_node = new json_sample.RootObject();
root_node.title = "Harry Potter and the Philosopher's Stone";
root_node.author = "J.K. Rowling";
root_node.tags = new List<string> { "novel", "story", "magic" };
root_node.valiableTags = new List<object> { 123, false, "str" };
root_node.intArray = new List<int> { 1, 2, 3, 4, 5 };
root_node.floatArray = new List<double> { 1.2, 1.3, 1.4, 2.0 };
root_node.date = "2016/11/29T12:34:56.000";
root_node.year = "1997";
//Hogeノード組み立て
var hoge_node = new Hoge();
hoge_node.stringField = "piyo";
hoge_node.numField = 123;
hoge_node.floatField = 20.315;
hoge_node.boolField = false;
//Hugaノード組み立て
var huga_node = new JsonNodeHoge.Huga();
huga_node.piyo = new List<string> { "orange",
"apple"};
//ノード関連付け
hoge_node.huga = huga_node;
root_node.hoge = hoge_node;
//出力
var jsonserializersettings = new JsonSerializerSettings();
//jsonconveet設定
jsonserializersettings.NullValueHandling = NullValueHandling.Ignore; //nullは出さない
jsonserializersettings.Formatting = Formatting.Indented; //JSON整形
var jsonString = JsonConvert.SerializeObject(root_node, jsonserializersettings);
MessageBox.Show(jsonString);
view raw sample.cs hosted with ❤ by GitHub

完成したサンプルコードはここに置いておきます。

0 件のコメント:

コメントを投稿