How to retrieve data with JSON as Firebase datasnapshot in Unity?
Asked Answered
S

0

1
[Serializable]
    public struct InventoryData
    {
        public int a;
        public BackpackData Backpack;
        public EquipmentData Equipment;
    }

    [Serializable]
    public struct BackpackData
    {
        public int[] Amounts;
        public int[] Items;
    }

    [Serializable]
    public struct EquipmentData
    {
        public int Boots;
        public int Gloves;
        public int Helmet;
        public Pocket LeftPocket;
        public int PrimaryWeapon;
        public Pocket RightPocket;
        public int SecondaryWeapon;
        public int Trousers;
        public int Vest;
    }

    [Serializable]
    public struct Pocket
    {
        public int Amount;
        public int Item;
    }

I use Firebase and data returns as dataSnaphsot.

public void Load(ICanLoadData sender, string path = "")
        {
            DataSnapshot dataSnapshot = null;
            DatabaseReference databaseReference;

            if (path == "")
            {
                databaseReference = firebaseDatabase.RootReference.Child("users")
                    .Child(FirebaseComponent.firebaseUser.UserId);
            }
            else
                databaseReference = firebaseDatabase.RootReference.Child("users")
                    .Child(FirebaseComponent.firebaseUser.UserId).Child(path);

            databaseReference.GetValueAsync().ContinueWith(task =>
            {
                if (task.IsFaulted)
                    sender.OnLoadProcessFaulted();
                if (task.IsCanceled)
                    sender.OnLoadProcessCanceled();
                if (!task.IsCompleted) return;
                dataSnapshot = task.Result;
                if (dataSnapshot.Exists)
                    sender.OnLoadProcessCompleted(dataSnapshot);
                else
                    sender.OnLoadProcessDataNotExists();
            });
        }

this method returns the datasnapshot. That method works correctly and returns expected data.

The data structure that I want to retrieve from database is like in the picture.

public void LoadData(DataSnapshot dataSnapshot)
        {
            try
            {
                inventoryData = JsonUtility.FromJson<InventoryData>(dataSnapshot.ToString());
            }
            catch (Exception e)
            {
                Debug.Log(e.Message);
                throw;
            }
        }

This is the method that I use to fetch data from JSON with giving datasnaphot. The snapshot returns right data. However program stops at this line. The error occurs and says that, json parse error: invalid value.

JSON parse error: Invalid value.
UnityEngine.Debug:Log (object)
ZombieShooter.Component.InventoryComponent:LoadData (Firebase.Database.DataSnapshot) (at Assets/Game Assets/Game/Components/InventoryComponent.cs:88)
ZombieShooter.Component.DataComponent:OnLoadProcessCompleted (Firebase.Database.DataSnapshot) (at Assets/Game Assets/Game/Components/DataComponent.cs:223)
ZombieShooter.Component.DatabaseComponent/<>c__DisplayClass5_0:<Load>b__0 (System.Threading.Tasks.Task`1<Firebase.Database.DataSnapshot>) (at Assets/Game Assets/Game/Components/Database/DatabaseComponent.cs:58)
System.Threading._ThreadPoolWaitCallback:PerformWaitCallback ()

As you can see the result of loading data method is correct. Result of Data Loading

In my opinion, the problem is related to struct type. I use nested data and this data type is struct. Probably JSON can't parse string to struct type. In that case, which alternative should I use? enter image description here enter image description here

and that is how data looks like in the database.

The result of Debug.log(dataSnapshot.ToString()

DataSnapshot { key = Inventory, value = System.Collections.Generic.Dictionary`2[System.String,System.Object] }
UnityEngine.Debug:Log (object)
ZombieShooter.Component.InventoryComponent:LoadData (Firebase.Database.DataSnapshot) (at Assets/Game Assets/Game/Components/InventoryComponent.cs:84)
ZombieShooter.Component.DataComponent:OnLoadProcessCompleted (Firebase.Database.DataSnapshot) (at Assets/Game Assets/Game/Components/DataComponent.cs:223)
ZombieShooter.Component.DatabaseComponent/<>c__DisplayClass5_0:<Load>b__0 (System.Threading.Tasks.Task`1<Firebase.Database.DataSnapshot>) (at Assets/Game Assets/Game/Components/Database/DatabaseComponent.cs:58)
System.Threading._ThreadPoolWaitCallback:PerformWaitCallback ()
Sloe answered 25/6, 2021 at 10:32 Comment(7)
Why not upload images of code/errors when asking a question?Misspend
@Misspend I haven't heard about that. I am changing right now. Thanks you very much. And sorry about that.Sloe
and just t be sure is your InventoryData also [Serializable] ? Could you post the result of Debug.Log(dataSnapshot.ToString()); ?Misspend
@Misspend I attached to questionSloe
@Misspend any progress?Sloe
well if your data snapshot is a dictionary then you won't be able to use it with the built-in JsonUtility but would need to use a third party library like e.g. Newtonsoft .NET JsonMisspend
@Misspend it still not working. Parsing operation finishes with errorSloe

© 2022 - 2024 — McMap. All rights reserved.