facebook twitter hatena line email

「Unity/Csharp/Json」の版間の差分

提供: 初心者エンジニアの簡易メモ
移動: 案内検索
(json展開)
(json展開)
行27: 行27:
 
         Debug.Log("status=" + resData.status);
 
         Debug.Log("status=" + resData.status);
 
         Debug.Log("notice=" + resData.notice);
 
         Debug.Log("notice=" + resData.notice);
         Debug.Log("notice=" + resData.user.name);
+
         Debug.Log("user.name=" + resData.user.name);
 
         foreach (string like in resData.user.likes) {
 
         foreach (string like in resData.user.likes) {
 
             Debug.Log("like=" + like);
 
             Debug.Log("like=" + like);

2018年12月8日 (土) 03:35時点における版

jsonを扱い方

Unity 5.3からJsonUtilityが使えるようになったので、JsonUtilityを使う。

使いたいpropertyだけ定義すればそれだけを取得することもできる。

json展開

json

{"status":"ok","notice":"message1","user":{"id":1,"name":"taro","likes":["tyoko","prin"]}}

サンプル

using System;
public class AuthScript : MonoBehaviour {
    [Serializable]
    class ResData {
        public string status = "ok";
        public string notice = "";
        public ResUser user;
    }
    [Serializable]
    class ResUser {
        public int id = 0;
        public string name = "";
        public string[] likes;
    }
    void ExecJsonParse (string json) {
       ResData resData = JsonUtility.FromJson<ResData>(json);
       Debug.Log("status=" + resData.status);
       Debug.Log("notice=" + resData.notice);
       Debug.Log("user.name=" + resData.user.name);
       foreach (string like in resData.user.likes) {
           Debug.Log("like=" + like);
       }
    }
}

以下エラーとなる場合は[Serializable]が足りない場合がある

NullReferenceException: Object reference not set to an instance of an object


[Serializable]を追加して以下エラーとなる場合はusing System;が足らない可能性がある。

error CS0246: The type or namespace name `Serializable' could not be found. Are you missing an assembly reference?

公式JsonUtility

https://docs.unity3d.com/ScriptReference/JsonUtility.html