Skip to content

Instantly share code, notes, and snippets.

@hagbarddenstore
Last active August 29, 2015 14:21
Show Gist options
  • Save hagbarddenstore/c7f05a7bb166a05534d9 to your computer and use it in GitHub Desktop.
Save hagbarddenstore/c7f05a7bb166a05534d9 to your computer and use it in GitHub Desktop.
The question is, how to parse JSON which contains a defined set of types, but allowing multiple types in an array.
class Animal {
protected Animal(string type)
{
Type = type;
}
public string Type { get; private set; }
}
class Dog : Animal
{
public Dog(string name) : base("Dog")
{
Name = name;
}
public string Name { get; private set; }
}
class Cat : Animal
{
public Cat(string name) : bsae("Cat")
{
Name = name;
}
public string Name { get; private set; }
}
class JsonObject
{
public Animal[] Animals { get; set; }
}
{
"animals": [
{
"type": "Dog",
"name": "Buster"
},
{
"type": "Cat",
"name": "Lucy"
}
]
}
type Animal struct {
Type string `json:"type"`
}
type Cat struct {
Animal
Name string `json:"name"`
}
type Dog struct {
Animal
Name string `json:"name"`
}
type JsonObject struct {
Animals []??? // Which type should I use? Doesn't compile with "Animal"
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment