简体   繁体   English

如何使用C#将对象序列化为json

[英]how to serialize object into json using c#

I tried using 我尝试使用

var myobject = JsonConvert.SerializeObject(Customer);

but problem is in Customer properties are like 但是问题在于Customer属性就像

FirstName and my service expecting json input like firstName {"firstName":"Neo"} FirstName和我的服务需要json输入,例如firstName {"firstName":"Neo"}

statement JsonConvert.SerializeObject(Customer); 声明JsonConvert.SerializeObject(Customer); gives me {"FirstName":"Neo"} which is wrong. 给我{"FirstName":"Neo"}这是错误的。

So How can I change first letter when JsonConvert.SerializeObject happened ? 那么,当JsonConvert.SerializeObject发生时,如何更改首字母?

Or How to take only one parameter as input json firstname instead if using Customer object. 或如果使用Customer对象,则如何仅将一个参数用作输入json firstname

You should use the Json.NET attribute support to customize the naming: 您应该使用Json.NET属性支持来自定义命名:

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

You can use like this. 您可以这样使用。 Use DataMember property, it'll serailize as mentioned. 使用DataMember属性,它将如前所述进行序列化。

[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. 使用webapi时,我们可以在webapi配置的register方法中定义一个CamelCasePropertyNamesContractResolver(json.net库的一部分)作为格式化程序。

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. 上面的代码特别是针对webapi的,但是,我相信当不使用webapi时,模拟方法可以作为解决方案。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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