Home > OS >  Json serialize and deserialize dynamic object in C#
Json serialize and deserialize dynamic object in C#

Time:10-14

Summary: I am required to submit a JSON request via C# where part of the payload changes based on certain business rules. I know all the possible structures, but have to use only the correct one in the request.

Example 1

{
"activity": {
        "referenceId": "",
            "data": {
                "rents": 0.0,
                "wages": 0.0
        }
    }
}

Example 2

{
"activity": {
        "referenceId": "",
            "data": {
                "transport": 0.0,
                "salaries": 0.0
        }
    }
}

Example 3

{
"activity": {
        "referenceId": "",
            "data": {
                "water": 0.0,
                "miscellaneous": 0.0
        }
    }
}

So, depending on some business rules, I have to change the parameters in "data". It's a bit more complex than just two property names, but I think the answer to this question as asked will be sufficient.

I have set up POCO's as per usual, but have no idea how to get them to work within this requirement.

I had the idea to create a "master" Data object and somehow only pass along the properties required, but I'm stumped at that point.

public class Rootobject
{
    public Activity activity { get; set; }
}

public class Activity
{
    public string referenceId { get; set; }
    public Data data { get; set; }
}

public class Data //Inheriting from this master won't work.
{
    public float water { get; set; }
    public float miscellaneous { get; set; }
    public float transport { get; set; }
    public float salaries { get; set; }
    public float rents { get; set; }
    public float wages { get; set; }
}

CodePudding user response:

I've made a lot of different solutions to handle JSON's like this, but in long term the best thing is simple Dictionary:

class Root
{
  public Activity Activity { get; set; }
}

class Activity
{
  public string ReferenceId { get; set; }
  public Dictionary<string, float> Data { get; set; }
}

Then, you can just map those object to whatever you want.

You can also read about converters and polimorphic deserialization, but it's not so easy. You have to manually detect discriminator (some unique field existing in one type) and... still, do it manually, in converter.

CodePudding user response:

Just use null property ignore functionality for all properties. Like this:

    [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)]
public float water { get; set; }

This attribute remove null data from your object.

  • Related