Can't load a List of object (<Item>) to firebase realtime database

Viewed 163

I'm developing a 2D game app using unity c#.

I have a list of item(object) and each item contains double Price, double Multiplier and int Level.

I'm trying to load that List to the FireBase Realtime DataBase using json inorder to save the player's peronal shop. to try and make it look like this in the DB:

DB should be like this

This is my Item class:

public class Item
{
    
    public double Price {get; set;}
    public double Multiplier { get; set; }
    public int Level { get; set; }
    

    public Item(double price, double multiplier, int level)
    {
        this.Price = price;
        this.Multiplier = multiplier;
        this.Level = level;
    }
}

And this is my Shop class:

public class Shop
{
    public List<Item> ShopList { get; set; }

    public Shop()
    {
        this.ShopList = new List<Item>();
    }

    public void InitShop()
    {
        string[] lines = System.IO.File.ReadAllLines(@"Assets\Scripts\Data\ShopData.txt");
        foreach (string line in lines)
        {
            string[] words = line.Split(',');
            double price = Convert.ToDouble(words[0]);
            double mul = Convert.ToDouble(words[1]);
            int level = Convert.ToInt32(words[2]);
            Item i = new Item(price, mul, level);
            this.ShopList.Add(i);
        }
    }
3 Answers

I would recommend using NewtonSoft /Json.Net for Unity. Pakcage can be found here:

https://assetstore.unity.com/packages/tools/input-management/json-net-for-unity-11347

Works like this:

string ConvertToJson(object obj) 
{
    return JsonConvert.SerializeObject(obj);
}

string ConvertFromJson<T>(string json)
{
    return JsonConvert.DeserializeObject<T>(json);
}


void Usage() 
{
    List<object> myList = populateListWithSomeData();
    
    // Save it
    var json = ConvertToJson(myList);
    SaveInDatabase(json);
    
    // Load it
    var json = LoadFromDatabase();
    myList = ConvertFromJson<List<object>>(json);
}

When you read from realtime db to Unity, it keeps the type data as keywords which is problematic to JSON.parse() these are most likely causing issues for your code, there is a JSON.parser that handles this, at the current time I am unable to find the script in mind.

an alternative from the community is to convert it to a dictionary

Dictionary<string, object> dict = new Dictionary<string, object>();
foreach (DataSnapshot child in snapshot.Children)
{
    dict.Add(child.Key, child.Value);
}
Related