Instance of JsonData Doesn't hold an int even though im typcasting..
Hey guys so i'm writing an inventory script passing data using JSON. I started following a guide online however I am casting the same way as him yet I am getting an error.
Here is my script I'm using (on a inventory game object in scene) using System.Collections; using System.Collections.Generic; using UnityEngine; using LitJson; using System.IO;
public class ItemDatabase : MonoBehaviour {
//creating a list to hold our database called databse
private List<Item> database = new List<Item>();
//creates jsondata object that holds all the data we pull in from the string
private JsonData itemData;
void Start()
{
//changes json data to a object this is pulling from streaming assets folder in assets from game (Streaming assets does not get built on build) people cant change items
//works as a dictionary
itemData = JsonMapper.ToObject (File.ReadAllText(Application.dataPath + "/StreamingAssets/Items.json"));
//running construct item method
ConstructItemDatabase ();
Debug.Log (database[1].Title);
}
//set up system to laod data from the json file
void ConstructItemDatabase()
{
//loops through the item data list to add it to the ItemDatabase
for (int i = 0; i < itemData.Count; i++)
{
database.Add (new Item ((int)itemData[i]["id"], itemData[i]["title"].ToString(), (int)itemData[i]["value"]));
}
}
}
//this will hold all the properites of the item ex. stats id name
public class Item
{
public int ID { get; set;}
public string Title { get; set;}
public int Value { get; set; }
public Item(int id, string title, int value)
{
this.ID = id;
this.Title = title;
this.Value = value;
}
}
This is my JSON script
[
{
"id": 0,
"title": "Shitty Sword",
"value": "6"
},
{
"id": 1,
"title": "Steel Gloves",
"value": "123"
}
]
I know it was to do with the way I am typecasting in the ConstructItemDatabase() but I dont understand why..
Please help Thanks
Answer by C-Hoy · Mar 13, 2017 at 02:59 AM
in your JSON script you're declaring the int in "value": between two " "
"value": "6" should actually be :
"value": 6
i made the same mistake and just realized it when i was googling to find the answer xD
Your answer
Follow this Question
Related Questions
JsonUtility not making JSONs 1 Answer
Armed Unity Parkour 0 Answers
Recursive JSON serialization / serialize list of custom serializable objects? 1 Answer
Deserialize Json array with mixed types 0 Answers