- Home /
Question by
Divunity · Aug 18, 2018 at 08:00 PM ·
jsondeserialization
Parsing from JSON NullReferenceException: Object reference not set to an instance of an object
JSON File
{
"values": [
"a",
"ability",
"able",
"about",
"above",
"abroad",
"absence",
"absent",
"absolute",
"accept",
"accident"
]
}
Helper Class
[System.Serializable]
public class NewUserDataFormat
{
public List<string> values { get; set; }
public NewUserDataFormat(List<string> l)
{
foreach (var VARIABLE in l)
{
values.Add(VARIABLE);
}
}
}
Parsing Method
private void LoadGameDataAsString()
{
var filePath = Application.dataPath + gameDataProjectFilePath;
if (File.Exists(filePath))
{
var dataAsJson = File.ReadAllText(filePath);
JDeserialize(dataAsJson as string);
}
else
{
Debug.Log("can't find file : " + filePath);
}
}
void JDeserialize(string jstring)
{
Debug.Log(jstring);
NewUserDataFormat sf = (NewUserDataFormat)JsonUtility.FromJson(jstring, typeof(NewUserDataFormat));
Debug.Log(sf.values.Count);//ERROR HERE
}
Please Help , Thank You in advance.
Comment
Best Answer
Answer by Bunny83 · Aug 18, 2018 at 10:25 PM
You declared "values" as auto-property. Unity doesn't serialize properties. The next thing is your contructor of your class doesn't work as you never initialize "values". You may want to declare it like this:
[System.Serializable]
public class NewUserDataFormat
{
public List<string> values = new List<string>();
public NewUserDataFormat(List<string> l)
{
values.AddRange( l );
}
}
You are the man . Thank youuuuuuuuu buddy. Thanks very much :) . Here - Have some points.
Answer by satya_jeetu · Sep 28, 2021 at 10:20 AM
use https://www.newtonsoft.com/json library Worked for me