- Home /
Deserializing Json String
Hi,
Im trying to deserialise a get request where i get a json back with the following
[{"GameName":"Game1","GameLocation":"Test1"},{"GameName":"Game2","GameLocation":"Test2"}]
Im useing the following script
using System.Collections;
using System.Collections.Generic;
namespace APP
{
[System.Serializable]
public class GameFinder
{
public string Token;
public string UserName;
public string CompanyName;
public string[] GameAreas;
public List<string> GameName = new List<string>();
public List<string> GameLocation = new List<string>();
//public string[] GameName;
//public string[] GameLocation;
// public string ProductName;
}
//And im using this
IEnumerator GetGameList(WWW www)
{
yield return www;
if (www.error == null)
{
Debug.Log("WWW List Ok!: " + www.text);
string data = JsonWriter.Serialize(www.text);
apb = JsonReader.Deserialize<APP.GameFinder>(www.text);
}
else
{
Debug.Log("WWW List Error: " + www.error);
}
}
Im getting this error
InvalidCastException: Cannot cast from source type to destination type.
Pathfinding.Serialization.JsonFx.JsonReader.Deserialize[GameFinder] (System.String value)
Answer by niall1111 · Sep 11, 2014 at 02:44 PM
In the same file, declare classes that will hold your JSON data, with variable names that exactly match the variable names in the JSON:
public class MyJSON{
public MyJSON(){}
public GameData[] games
}
public class GameData{
public string GameName;
public string GameLocation;
}
public MyJSON jsonData;
Then in your code, you need something like this:
jsonData = JsonReader.Deserialize<MyJSON>(www.text);
It may take some fiddling around, i'm doing this from memory, but it's the same concept I've used for dealing with JSON anyway...
I tried your solution, but i still get
InvalidCastException: Cannot cast from source type to destination type.Pathfinding.Serialization.JsonFx.JsonReader.Deserialize[$$anonymous$$yJSON] (System.String value)Connection$$anonymous$$anager+c__Iterator2.$$anonymous$$oveNext () (at Assets/Scripts/Connection$$anonymous$$anager.cs:145)
I having no problem retriving Token, UserName and CompanyName.
But its not the same layout the string is outputting. I cant change the output of the otherstring btw.
I have verified the string in [http://jsonformatter.curiousconcept.com/][1], to be sure it was valid.
Your answer
Follow this Question
Related Questions
Multiple Cars not working 1 Answer
Distribute terrain in zones 3 Answers
JsonFX and Polymorphism? 1 Answer
Making a bubble level (not a game but work tool) 1 Answer
An OS design issue: File types associated with their appropriate programs 1 Answer