Serialize list count instead of list

Viewed 161

I am logging the XML request that is received by the web service in JSON file. We have a class with all the attributes as follows:

class RequestExternal
{
  [XmlAttribute("FirstName")]
  [JsonProperty]
  public string Firstname{get; set;}

  [XmlAttribute("FirstName")]
  [JsonProperty]
  public string LastName{get; set;}

  [XmlAttribute("FirstName")]
  [JsonProperty] -- To be changed : Want to log this as PaymentCards.Count
  public List<Object> PaymentCards{get; set;}
}

I want to log this request as:

{
  FirstName: 'XXX',
  LastName: 'XXX',
  PaymentCount: **count of PaymentCard list**
}

Is there a way to do it via JsonConverter or something?

I can do it by introducing a new derived property.

But that will not work for me. we have a documentation mechanism which will expose those new property to the clients.

1 Answers

Depending in the specifics of your use case and if you have access to the class definition. You could easily write a converter and annotate the property

Given

public class ListToCountConverter : JsonConverter<IList>
{
   public override void WriteJson(JsonWriter writer, IList value, JsonSerializer serializer)
      => writer.WriteValue(value.Count);

   public override IList ReadJson(JsonReader reader, Type objectType, IList existingValue, bool hasExistingValue, JsonSerializer serializer)
       => throw new NotImplementedException();
}

Your Class

class RequestExternal
{
   ...
   [JsonProperty] 
   [JsonConverter(typeof(ListToCountConverter))]
   public List<Object> PaymentCards { get; set; }
}

Example

var test = new RequestExternal()
{
   Firstname = "Bob",
   LastName = "Derp",
   PaymentCards = new List<object>(){null,null,null}
};

var result = JsonConvert.SerializeObject(test, Formatting.Indented);
Console.WriteLine(result);

Output

{
  "Firstname": "Bob",
  "LastName": "Derp",
  "PaymentCards": 3
}
Related