c# 对象json互相转换,将C#对象转换为Json对象

I am trying to serialize a C# object into a Json object. That will then be submitted to the Salesforce API, and create an application. Right now I have the C# object serialized into a Json string, but I need it to be an object.

Here is my C# object along with accompany serialization.

Customer application = new Customer {

ProductDescription = "gors_descr " + tbDescription.Text,

Fname = "b_name_first " + tbFName.Text,

Lname = "b_name_last " + tbLName.Text

};

var json = new System.Web.Script.Serialization.JavaScriptSerializer();

string jsonString = json.Serialize(application);

string endPoint = token.instance_url + "/services/apexrest/submitApplication/";

string response = conn.HttpPost(endPoint, json, token);

Literal rLiteral = this.FindControl("resultLiteral") as Literal;

I need the JSON string to output inside of a JSON Object. An example of what I need is below:

"{ \"jsonCreditApplication\" : " +

"\"gors_descr\" : \"Appliances\", " +

"\"b_name_first\" : \"Marisol\", " +

"\"b_name_last\" : \"Testcase\", " +

"}";

This hard coded json string is inside of an object. As it stands, the values in the C# object are being outputted into a JSON string, but I'm needing it output into an object so that the Salesforce API will accept the submission.

How can I append or insert the JSON string into an object?

解决方案

To create correct JSON first you need to prepare appropriate model. It can be something like that:

[DataContract]

public class Customer

{

[DataMember(Name = "gors_descr")]

public string ProductDescription { get; set; }

[DataMember(Name = "b_name_first")]

public string Fname { get; set; }

[DataMember(Name = "b_name_last")]

public string Lname { get; set; }

}

To be able to use Data attributes you will need to choose some other JSON serializer. For example DataContractJsonSerializer or Json.NET(I will use it in this example).

Customer customer = new Customer

{

ProductDescription = tbDescription.Text,

Fname = tbFName.Text,

Lname = tbLName.Text

};

string creditApplicationJson = JsonConvert.SerializeObject(

new

{

jsonCreditApplication = customer

});

So jsonCreditApplication variable will be:

{

"jsonCreditApplication": {

"gors_descr": "Appliances",

"b_name_first": "Marisol",

"b_name_last": "Testcase"

}

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值