Wayback Machinekoobas.hobune.stream
May JUN Jul
Previous capture 14 Next capture
2021 2022 2023
2 captures
12 Jun 22 - 14 Jun 22
sparklines
Close Help
  • Products
  • Solutions
  • Made with Unity
  • Learning
  • Support & Services
  • Community
  • Asset Store
  • Get Unity

UNITY ACCOUNT

You need a Unity Account to shop in the Online and Asset Stores, participate in the Unity Community and manage your license portfolio. Login Create account
  • Blog
  • Forums
  • Answers
  • Evangelists
  • User Groups
  • Beta Program
  • Advisory Panel

Navigation

  • Home
  • Products
  • Solutions
  • Made with Unity
  • Learning
  • Support & Services
  • Community
    • Blog
    • Forums
    • Answers
    • Evangelists
    • User Groups
    • Beta Program
    • Advisory Panel

Unity account

You need a Unity Account to shop in the Online and Asset Stores, participate in the Unity Community and manage your license portfolio. Login Create account

Language

  • Chinese
  • Spanish
  • Japanese
  • Korean
  • Portuguese
  • Ask a question
  • Spaces
    • Default
    • Help Room
    • META
    • Moderators
    • Topics
    • Questions
    • Users
    • Badges
  • Home /
avatar image
1
Question by huialx · Feb 03, 2017 at 08:41 PM · jsondeserializationdeserialize

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

Hi, so i'm trying to create a "PlayerStats" object using the JsonUtility class. There are no errors in the Editor but whenever i run the code i get the Exception : System.ArgumentException: Cannot deserialize JSON to new instances of type 'PlayerStats.' and i don't know why. I use the method just like they do in the documentation but i keep getting that exception. The json file was created using JU.ToJson and should work without problem. What am i missing ?

             if (File.Exists(savePath + "\\" + name + ".json")) {
                 string saveData = File.ReadAllText(savePath + "\\" + name + ".json");
                 GameObject localPlayer = (GameObject)Instantiate(Resources.Load("Player/" +                                                              JsonUtility.FromJson<PlayerStats>(saveData).race.ToString()));
             }


the json file :

 {
     "race": 0,
     "playerName": "xxx",
     "initative": 10.0
 }

PlayerStats.cs :

 public class PlayerStats : MonoBehaviour {
     public Race race;
     public string playerName;
 
     public float initative = 10;
     // Use this for initialization
     void Start () {
         
     }
     
     // Update is called once per frame
     void Update () {
     
     }
 }
Comment
Add comment · Show 4
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users
avatar image huialx · Feb 03, 2017 at 04:39 PM 0
Share

Update: Looks like i can create PlayerStats object from within the PlayerStats script with JsonUtility.FromJson but not within any other script.

avatar image FortisVenaliter huialx · Feb 03, 2017 at 08:42 PM 0
Share

Post the definition of the PlayerStats class as well, please.

avatar image estevan95 FortisVenaliter · Feb 04, 2017 at 01:47 AM 0
Share

That. I suppose PlayerStats has a different definition from what the Json describes.

Show more comments

2 Replies

· Add your reply
  • Sort: 
avatar image
15
Best Answer

Answer by Bunny83 · Feb 04, 2017 at 03:56 PM

"PlayerStats" should not be a MonoBehaviour. The JsonUtility can only be used for data classes. MonoBehaviours are components which need to be attached to gameobjects. You can't simply "create" an instance, that's why it failed.

Try:

 [System.Serializable]
 public class PlayerStats
 {
     public Race race;
     public string playerName;
     
     public float initative = 10;
 }

Of course this class can not be attached to a gameobject. It's only ment as a data class that represents your save data. Also note that the "Race" class also can't be a MonoBehaviour. All classes you want to save / restore have to be normal serializable classes (or maybe derived from ScriptableObject, though i never used that JsonUtility myself).

Comment
Add comment · Show 3 · Share
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users
avatar image Bunny83 · Feb 04, 2017 at 03:59 PM 0
Share

ps: by looking at your json data it looks like your "race" is actually a number. I doubt that it can create a "Race" instance from a number. Have you created that Json data yourself?

avatar image huialx Bunny83 · Feb 04, 2017 at 04:51 PM 0
Share

"Race" is just an enum and the json was created using JasonUtility.ToJson(). I see, eventhough it's strange i can create multiple PlayerStats object from within the PlayerStats script. I have created my own Jsonparser for my use-case but i will keep it in $$anonymous$$d incase i use JsonUtility in the future. Thanks.

avatar image DSivtsov · Feb 18 at 03:47 PM 0
Share

Not fully correct answer watch below answer @gz7190

avatar image
11

Answer by gz7190 · Aug 28, 2019 at 05:52 PM

In case anyone else comes across this and still wants to serialize MonoBehaviour or ScriptableObject, the fine print in the docs state the following:

However, when deserializing JSON into subclasses of MonoBehaviour or ScriptableObject, you must use FromJsonOverwrite; FromJson is not supported and will throw an exception.

source: https://docs.unity3d.com/Manual/JSONSerialization.html

Comment
Add comment · Show 1 · Share
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users
avatar image unity-marcus · Feb 18, 2020 at 10:25 AM 0
Share

Thanks for pointing this out, this finally solved my problem deserializing a ScriptableObject from JSON!

Your answer

Hint: You can notify a user about this post by typing @username

Up to 2 attachments (including images) can be used with a maximum of 524.3 kB each and 1.0 MB total.

Follow this Question

Answers Answers and Comments

8 People are following this question.

avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image

Related Questions

JSON invalid value 1 Answer

Deserialize Json into list.,how to deserialize a list via .FromJson 1 Answer

Having issues when multithreading and deserializing JSON with JSONUtility 1 Answer

Read JSON from Facebook? 0 Answers

Deserializing JSON 1 Answer


Enterprise
Social Q&A

Social
Subscribe on YouTube social-youtube Follow on LinkedIn social-linkedin Follow on Twitter social-twitter Follow on Facebook social-facebook Follow on Instagram social-instagram

Footer

  • Purchase
    • Products
    • Subscription
    • Asset Store
    • Unity Gear
    • Resellers
  • Education
    • Students
    • Educators
    • Certification
    • Learn
    • Center of Excellence
  • Download
    • Unity
    • Beta Program
  • Unity Labs
    • Labs
    • Publications
  • Resources
    • Learn platform
    • Community
    • Documentation
    • Unity QA
    • FAQ
    • Services Status
    • Connect
  • About Unity
    • About Us
    • Blog
    • Events
    • Careers
    • Contact
    • Press
    • Partners
    • Affiliates
    • Security
Copyright © 2020 Unity Technologies
  • Legal
  • Privacy Policy
  • Cookies
  • Do Not Sell My Personal Information
  • Cookies Settings
"Unity", Unity logos, and other Unity trademarks are trademarks or registered trademarks of Unity Technologies or its affiliates in the U.S. and elsewhere (more info here). Other names or brands are trademarks of their respective owners.
  • Anonymous
  • Sign in
  • Create
  • Ask a question
  • Spaces
  • Default
  • Help Room
  • META
  • Moderators
  • Explore
  • Topics
  • Questions
  • Users
  • Badges