Reputation: 15796
Here's my code that converts a Json to a class of my own:
JSONArray boats = p["data"]["game"]["start"]["boats"].AsArray;
j.data.game.start.boats = new JsonGameDetailBoat[boats.Count];
for (int i = 0; i < boats.Count; i++) {
JSONNode boat = boats[i];
j.data.game.start.boats[i] = new JsonGameDetailBoat {
name = boat["name"],
total = boat["total"]
};
}
JSONArray board = p["data"]["game"]["board"].AsArray;
j.data.game.board = new JsonGameDataCell[board.Count][];
for (int i = 0; i < board.Count; i++) {
/* almost same code than previous loop */
}
Watch the last lines: I have to make another loop, to make the same thing.
And I'll have to do this 4 more times.
So I'm trying to make a generic that would convert a JSONArray to a custom class, and fetch each properties of as string and read them from the JSON array.
My code looks like this but it doesn't work, and I dont know if it's possible to enumerate the public properties of a class.
public class JSONArrayConverter<T>
{
public JSONArrayConverter(JSONNode p)
{
JSONArray tab = p.AsArray;
IList<T> result;
for (int i = 0; i < tab.Count; i++) {
JSONNode value = tab[i];
result[i] = new <T>();
}
}
}
This code doesn't work, I'm stuck here: result[i] = new <T>();
Upvotes: 0
Views: 94
Reputation: 1167
You can use Reflection
public JSONArrayConverter(JSONNode p)
{
JSONArray tab = p.AsArray;
IList<T> result = new List<T>();
for (int i = 0; i < tab.Count(); i++)
{
JSONNode value = tab[i];
result[i] = (T)Activator.CreateInstance(typeof(T), value);
}
}
or an interface:
public interface JSONConvertable
{
void Initialise(JSONNode node);
}
public class JSONArrayConverter<T> where T : JSONConvertable, new()
{
public JSONArrayConverter(JSONNode p)
{
JSONArray tab = p.AsArray;
IList<T> result = new List<T>();
for (int i = 0; i < tab.Count(); i++)
{
JSONNode value = tab[i];
result[i] = new T();
result[i].Initialise(value);
}
}
}
EDIT:
Or callback
public JSONArrayConverter(JSONNode p, Func<JSONNode, T> creator)
{
JSONArray tab = p.AsArray;
IList<T> result = new List<T>();
for (int i = 0; i < tab.Count(); i++)
{
JSONNode value = tab[i];
result[i] = creator(value);
}
}
Upvotes: 2