万年素人からHackerへの道

万年素人がHackerになれるまで殴り書きするぜ。

  • ・資産運用おすすめ
    10万円は1000円くらい利益
    資産運用ブログ アセマネ
    • ・寄付お願いします
      YENTEN:YYzNPzdsZWqr5THWAdMrKDj7GT8ietDc2W
      BitZenny:ZfpUbVya8MWQkjjGJMjA7P9pPkqaLnwPWH
      c0ban:8KG95GXdEquNpPW8xJAJf7nn5kbimQ5wj1
      Skycoin:KMqcn7x8REwwzMHPi9fV9fbNwdofYAWKRo

    ResourcesLoadからJSONのデータ読み込みでハマる ※LitJsonを使用

    C#で書いた。

    ・Names.txtファイルの中身

    {
    "name"  : "Bill",
    "age"   : 32,
    "awake" : true,
    "n"     : 1994.0226,
    "note"  : [ "life", "is", "but", "a", "dream" ]
    }

    ※注意するのは、"は1つにする。例えばマニュアルのように(http://litjson.sourceforge.net/doc/manual.html)「""name"" : ""Bill"",」はだめ
    これはプログラム内の文字列で行なっていたため""となってたのだ。

    ・ハマったのはここ!
    ↓これはだめだ。拡張子がダメ。

            // json
            string fileName = "Names.json"; //  N/A!!
            TextAsset txt = Instantiate(Resources.Load("Text/" + fileName)) as TextAsset;
            string json = txt.text;
            JsonReader reader = new JsonReader (json);
    

    Unityの公式ドキュメントに
    http://docs.unity3d.com/Documentation/Components/class-TextAsset.html
    ファイル自体の拡張子は「.json」ではなく「.txt」「.xml」・・・・等々にするべきとあった。

    また、プログラム側で拡張子付けないこと!

    それらを踏まえてこのようにサンプルコードを置き換えた。Start()とかに書いてうまく言った。

            // json
            string fileName = "Names"; // not .json
            TextAsset txt = Instantiate (Resources.Load ("Text/" + fileName)) as TextAsset;
            string json = txt.text;
            JsonReader reader = new JsonReader (json);
    
            Debug.Log (new string ('-', 42));
    
            // The Read() method returns false when there's nothing else to read
            while (reader.Read ()) {
                string type = reader.Value != null ?
                    reader.Value.GetType ().ToString () : "";
    
                Debug.Log (reader.Token + "|" + reader.Value + "|" + type);
            }
    

    ・ログの結果こうなります
    ※出力に直接関係しない要らない部分は削除してます

    ------------------------------------------
    ObjectStart||
    PropertyName|name|System.String
    String|Bill|System.String
    PropertyName|age|System.String
    Int|32|System.Int32
    PropertyName|awake|System.String
    Boolean|True|System.Boolean
    PropertyName|n|System.String
    Double|1994.0226|System.Double
    PropertyName|note|System.String
    ArrayStart||
    String|life|System.String
    String|is|System.String
    String|but|System.String
    String|a|System.String
    String|dream|System.String
    ArrayEnd||
    ObjectEnd||