본문 바로가기

Unity

[Unity][c#] Firebase 에서 받은 데이터를 객체로 변환하기

유니티에서 파이어베이스의 값을 가져와 dictionary형태로 받았는데, 바로 내가 원하는 오브젝트 형식으로 변환해서 관리하고싶을때 이 방법을 사용하면 된다.

 

 

 

스태틱 클래스 생성

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
public static class ObjectExtensions
{
    public static T ToObject<T>(this IDictionary<stringobject> source)
        where T : classnew()
    {
            var someObject = new T();
            var someObjectType = someObject.GetType();
 
            foreach (var item in source)
            {
                someObjectType
                         .GetProperty(item.Key)
                         .SetValue(someObject, item.Value, null);
            }
 
            return someObject;
    }
 
    public static IDictionary<stringobject> AsDictionary(this object source, BindingFlags bindingAttr = BindingFlags.DeclaredOnly | BindingFlags.Public | BindingFlags.Instance)
    {
        return source.GetType().GetProperties(bindingAttr).ToDictionary
        (
            propInfo => propInfo.Name,
            propInfo => propInfo.GetValue(source, null)
        );
 
    }
}
 
 
 
cs

 

사용 예시

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
public void LoadData(){
 
    FirebaseDatabase.DefaultInstance.GetReference("USERDATA/" + usercode).GetValueAsync().ContinueWith(task =>
        {
            if (task.IsFaulted)
            {
                Debug.LogError("load ACCOUNT data from firebase : faulted!");
            }
            else if (task.IsCompleted)
            {
                DataSnapshot snapshot = task.Result;
                Dictionary<string,object> dictUser = (Dictionary<string,object>)snapshot.Value; //스냅샷을 가져옴.

                DB_BASICINFO info = dictUser.ToObject<DB_BASICINFO>();//dictionary 를 db_basicinfo의 객체로 변환
                
//obj to dictionary
//Dictionary<string,object> re_convert = info.AsDictionary().ToDictionary(item => item.Key, item => item.Value);
            }
        });
}
 
cs
 
   

13~15번째 줄을 참고하면 된다. 참고로, 위 스크립트는 dictionry -> object 도 가능하고 object -> dictionary 로의 변환도 가능하다.