0

It feels like I have a simple problem. I've got a data class with a couple of generic collections and I'd like to have them serialized as well. Reading the Internet here's what I'm doing:

The class:

public class QuestModel
{
    public string NameTag { get; set; }
    public string DescTag { get; set; }
    public int QuestLevel { get; set; }
    public Queue<QuestObjectiveBase> Objectives { get; set; }
    public List<QuestRewardBase> Rewards { get; set; }
    public bool Completed { get; set; }
    public bool TrackingProgress { get; set; }

    public QuestModel()
    {
        Objectives = new Queue<QuestObjectiveBase>();
        Rewards = new List<QuestRewardBase>();
        TrackingProgress = false;
        Completed = false;
    }
}

The code:

var json = JsonConvert.SerializeObject(sideQuests[0].Model, Formatting.Indented, new JsonSerializerSettings
{
    TypeNameHandling = TypeNameHandling.Auto
});

The output:

{
  "NameTag": "QUESTS_TEST_NAME",
  "DescTag": "QUESTS_TEST_DESC",
  "QuestLevel": 10,
  "Objectives": [
    {
      "$type": "Warlocks.Gameplay.Quests.Impl.Objectives.KillEnemiesQuestObjective, Assembly-CSharp"
    }
  ],
  "Rewards": [
    {
      "$type": "Warlocks.Gameplay.Quests.Impl.Rewards.GoldQuestReward, Assembly-CSharp"
    }
  ],
  "Completed": false,
  "TrackingProgress": true
}

As you can see there's only a type identifier in each of the Objective/Reward object. But there are no values.

user1255410
  • 856
  • 1
  • 9
  • 15
  • 1
    Does `KillEnemiesQuestObjective` have any public properties or fields? Only public members and those marked with `[JsonProperty]` are serialized, see http://www.newtonsoft.com/json/help/html/serializationguide.htm#Objects – dbc Nov 10 '16 at 10:33
  • Oh crap, that took me way too long to figure out. Thanks @dbc! However, now there's a problem with deserialization. Apparently JSON .net tries to instantiate abstract class members KillEnemiesQuestObjective and not the types it specified. – user1255410 Nov 10 '16 at 10:37
  • You have to use `TypeNameHandling.Auto` in deserialization as well. See https://stackoverflow.com/questions/40499272/json-deserialization-of-derived-types/40514862#40514862 – dbc Nov 10 '16 at 10:41
  • I used that. I fixed it by adding `MetadataPropertyHandling = MetadataPropertyHandling.ReadAhead` to my settings. – user1255410 Nov 10 '16 at 10:53

0 Answers0