본문 바로가기
Programming/Unity

[Unity ] json 오류 역직렬화 실패(cannot deserialize)

by Hello2 2022. 1. 17.

Json파일로 읽고 쓰기 위해 테스트를 해보던 중

클래스를 Json스트링으로 변환하는건 잘 되는데,

Json스트링을 다시 해당 클래스 타입의 객체로 변환해줄려니까 다음과 같은 오류가난다!

 

ArgumentException: Cannot deserialize JSON to new instances of type 'JsonTestClass.'
UnityEngine.JsonUtility.FromJson (System.String json, System.Type type) (at

 

해결방법은

https://answers.unity.com/questions/1308015/jsonutility-cannot-deserialize-json-to-new-instanc.html

 

[JsonUtility] cannot deserialize json to new instances of type X - Unity Answers

 

answers.unity.com

오 구세주님

 

바로 직렬화하려는 클래스에서 MonoBehaviour 상속을 없애주면 된다!!

 

이유는?

MonoBehaviour는 해당 클래스를 컴포넌트로 만든다는 것을 의미한다.

Unity에서 컴포넌트는 객체를 생성할 수 없고 GameObject에 붙어서 동작하게 된다.

여기서! Json스트링으로는 만들어지지만, Json스트링을 다시 객체로 만들려고 할 때, MonoBehaviour 때문에 객체가 만들어지지 못한다.

그래서 다음과 같은 오류가 뜬다.

 

노란색 경고문도 다 이유가 있어서 뜨는거였구나!