LoginSignup
9
10

More than 5 years have passed since last update.

C# で LitJSON を用いて気軽に JSON データを作る

Last updated at Posted at 2015-06-16

概要

JSON 形式のデータを生成(エンコード)したい。

LitJSON を使う

LitJSON を使うのが良い。
.NET であれば http://lbv.github.io/litjson/ から LitJson.dll を入手し、参照を追加すると良い。
Unity であれば初めから使えるっぽい。

元になるオブジェクトを作る

data.cs
var obj = new
{
    hoge = 10,
    fuga = "hello",
    abc = new[] { 10, 20, 30 },
    aaa = new[] { "x", "yy", "zzz" },
};

シンプルな変換

sample1.cs
string json = LitJson.JsonMapper.ToJson(obj);

結果

{"hoge":10,"fuga":"hello","abc":[10,20,30],"aaa":["x","yy","zzz"]}

人が見やすい形にする

sample2.cs
LitJson.JsonWriter writer1 = new LitJson.JsonWriter();
writer1.PrettyPrint = true;
writer1.IndentValue = 4;
LitJson.JsonMapper.ToJson(obj, writer1);
string json = writer1.ToString();

結果


{
    "hoge" : 10,
    "fuga" : "hello",
    "abc"  : [
        10,
        20,
        30
    ],
    "aaa"  : [
        "x",
        "yy",
        "zzz"
    ]
}
9
10
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
9
10