Saturday, August 19, 2017

c# - Deserialise Nested JSON with JSON Utility Unity 5.4


This is what my JSON looks like: {"series":[{,"points":[{"ts":"1473850836254","value":"11.27"},{"ts":"1473851256637","value":"6.44"}]}]}


I am trying to access the values in "points" by calling something like: data.series.points[0].ts



    Void Start(){
IncomingData data = IncomingData.CreateFromJSON(jsonResponse.text);
print("Series point length" + data.series.points.Count);
print("Series point 0" + data.series.points.get_Item[0].ts); // error
}

//----------------------------------------- classes -------------------------


    [System.Serializable]
public class IncomingData
{

public Series series;
public static IncomingData CreateFromJSON(string json)
{
return JsonUtility.FromJson(json);
}
}

[System.Serializable]
public class Series
{

public List points = new List { };
}


[System.Serializable]
public class Points
{
public int ts;
public int value;
}


My error:


// error CS0021: Cannot apply indexing with [] to an expression of type `method group'



Answer



You say you want to use data.series.points[0].ts but then you... don't, you use data.series.points.get_Item[0].ts


The thing you say you want to use works perfectly fine so let's dig into why the other thing is not working:



  • get_Item is a function, not a field or property. So you need to call it with (0) and not with [0]

  • get_Item is a magical function that should never ever be called directly. There is a special error for it as well (CS0571, "cannot explicitly call operator or accessor").

  • get_Item is called if you use the syntax points[0], the compiler translates this to .get_Item(0) so you can use the neat looking fancy syntax and not worry about anything.



No comments:

Post a Comment

Simple past, Present perfect Past perfect

Can you tell me which form of the following sentences is the correct one please? Imagine two friends discussing the gym... I was in a good s...