How to add mapper to JavaScriptSerializer().Serialize to get custom(minified) json without using [JsonProperty("")]?

90 views Asked by At

I want to customize JavaScriptSerializer().Serialize by adding mapping. Make it clear:

Think we have class:(as it comes from other library I can't modify this class, so I can not use [JsonProperty("")] )

class Address
{
     public string Number { get; set; }
     public string Street { get; set; }
     public string City { get; set; }
     public string Country { get; set; }
}

output should be:

{
         "NMB" : "No 25",
         "STR" : "Main Street",
         "CTY" : "Matale",
         "CNT" : "Sri Lanka"
 }

How can I achieve mapping during JavaScriptSerializer().Serialize(Address_Object);?

1

There are 1 answers

5
Serge On

IMHO, the simpliest way would be to create an util to serialize, you can use a net serializer, or a Newtonsoft.Json one

var addr = new Address {....}
string json = SerializeAddress(addr);

public string SerializeAddress(Address address)
{
    var addr = new
    {
        NMB = address.Number,
        STR = address.Street,
        CTY = address.City,
        CNT = address.Country
    };

    return Newtonsoft.Json.JsonConvert.SerializeObject(addr, Newtonsoft.Json.Formatting.Indented);
    //Or
    return System.Text.Json.JsonSerializer.Serialize(addr);
}