简体   繁体   中英

how to serialize object into json using c#

I tried using

var myobject = JsonConvert.SerializeObject(Customer);

but problem is in Customer properties are like

FirstName and my service expecting json input like firstName {"firstName":"Neo"}

statement JsonConvert.SerializeObject(Customer); gives me {"FirstName":"Neo"} which is wrong.

So How can I change first letter when JsonConvert.SerializeObject happened ?

Or How to take only one parameter as input json firstname instead if using Customer object.

You should use the Json.NET attribute support to customize the naming:

public class Customer
{
    [JsonProperty("firstName")]
    public string FirstName { get; set; }
}

You can use like this. Use DataMember property, it'll serailize as mentioned.

[DataContract(Namespace = "")]
public class Customer 
{
    [DataMember(Name = "firstName")]
    public string FirstName { get; set; }
}

You can define how data need to be serialized. When using webapi, we can define a CamelCasePropertyNamesContractResolver (part of json.net library) as formatter in the register method of the webapi config.

public static class WebApiConfig
{
    public static void Register(HttpConfiguration config)
    { 
       config.Formatters.JsonFormatter.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver();            
    }
}

The code above is especially for webapi, nevertheless I believe a simular approach can be a solution when not using webapi.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM