-1

e.g.

i got a class named Person:

public class Person
{
   public string Name { get; set; } 
   public DateTime Birth { get; set; }
}

and i want to convert this object to a customer json string like this { "Name":"Tom", "Birth":{"Year":1999,"Month":12,"Day":1} }

  • You can use a view model to achieve that – Dronacharya Jan 30 '18 at 13:27
  • a little bit of googling can help a lot. Take a [look](http://www.c-sharpcorner.com/article/json-serialization-and-deserialization-in-c-sharp/) – Nino Jan 30 '18 at 13:29
  • 1
    Possible duplicate of [Custom type serializer for Json.Net](https://stackoverflow.com/questions/20140472/custom-type-serializer-for-json-net) – Jakub Jankowski Jan 30 '18 at 13:32

2 Answers2

0

declare two class:

public class BirthDay
{
    public int Year { get; set; }
    public int Month { get; set; }
    public int Day { get; set; }
}

public class Person
{
    public string Name { get; set; }
    public BirthDay Birth { get; set; }
}
0

In case you don't want an additional class, you can achieve this by returning an object

public class Person
{
   public string Name { get; set; } 
   public DateTime BirthDateTime { get; set; }
   public object Birth => new {
       Year = BirthDateTime.Year,
       Month = BirthDateTime.Month,
       Day = BirthDateTime.Day,
   };
}

Also you'll have to add the [JsonIgnore] over the DateTime property if you don't want it serialized:

[JsonIgnore]
public DateTime BirthDateTime { get; set; }

I would recommend this method only if the class is used only as a DTO

Alex
  • 3,689
  • 1
  • 21
  • 32