R Bowen
R Bowen

Reputation: 77

Serializing and Deserializing multiple classes into one JSON object? Without attribute tags

I'm working on a project where I've been trying to keep code as modular as possible.

I want to now save/load objects to JSON, however I do not want every single class to be saved in hundreds of files as I want the json to be readable and easy to edit in one place for users.

For the sake of example, here is a sample of the C#:

 public class ObjectToBeSerialized
 {
     public float aNumber;
 }

 public class LinkingClass
 {
     public ObjectToBeSerialized linkedObject;
     public string aString;
 }

 public class OtherLink
 {
     public ObjectToBeSerialized linkedObject;
     public bool isThisObjectNice;
 }

So if I serialized this, the outcome I'm looking for would be like so:

{ "aNumber": 0, "aString": "Hello World", "isThisObjectNice": true }

So that it looks like it's one object to someone editing the json but in the code it is still a highly separated series of parts.

It is also important not to use attribute tags to keep the JSON separate from the code. I'm looking to use a ContractResolver or similar.

Upvotes: 0

Views: 1372

Answers (1)

Yakimych
Yakimych

Reputation: 17752

Assuming that by "keeping JSON separate from the code" you mean that you want to separate your domain model from any JSON serialization concerns, I think it's a good idea. The simplest way of doing it would be introducing a lightweight class for the purpose of modelling your output, as well as a mapping function:

public class ModelOfWhateverJsonShouldLookLike
{
    public float aNumber { get; set; }
    public string aString { get; set; }
    public bool isThisObjectNice { get; set; }
}

public static ToJsonModel(LinkingClass linkingObject, OtherLink otherLinkObject)
{
    return new ModelOfWhateverJsonShouldLookLike
    {
        aNumber = linkingObject.aNumber, // otherLinkObject.aNumber?
        aString = linkingObject.aString,
        isThisObjectNice = otherLinkObject.isThisObjectNice
    };
}

Before serializing, you would have to simply call the mapping function rather than serializing your domain objects.

The advantage of this approach is transparency and simplicity: it is easy to see exactly what is being serialized and debug the mapping function if things go wrong. Using a more "magical" approach with e.g. ContractResolver, might save some boilerplate with larger objects, but becomes a real pain (and a time-killer) when things go wrong.

An unrelated note: I would recommend sticking to C# naming conventions in C# code and naming public properties using UpperCamelCase: IsThisObjectNice. If you absolutely don't want to use a JsonProperty attribute, then you could keep the lowercase property names in the ModelOfWhateverJsonShouldLookLike.

Upvotes: 1

Related Questions