我正在尝试将 C# 对象序列化为 Json 对象。然后将其提交给 Salesforce API,并创建一个应用程序。现在我将 C# 对象序列化为 Json 字符串,但我需要它是一个对象。
这是我的 C# 对象以及随附的序列化。
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;
我需要在 JSON 对象中输出 JSON 字符串。下面是我需要的示例:
"{ \"jsonCreditApplication\" : " +
"\"gors_descr\" : \"Appliances\", " +
"\"b_name_first\" : \"Marisol\", " +
"\"b_name_last\" : \"Testcase\", " +
"}";
这个硬编码的 json 字符串在对象内部。就目前而言,C# 对象中的值被输出到一个 JSON 字符串中,但我需要它输出到一个对象中,以便 Salesforce API 将接受提交。
如何将 JSON 字符串追加或插入到对象中?
最佳答案
要首先创建正确的 JSON,您需要准备适当的模型。它可以是这样的:
[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; }
}
要能够使用 Data
属性,您需要选择其他一些 JSON 序列化程序。例如DataContractJsonSerializer或 Json.NET (我将在这个例子中使用它)。
Customer customer = new Customer
{
ProductDescription = tbDescription.Text,
Fname = tbFName.Text,
Lname = tbLName.Text
};
string creditApplicationJson = JsonConvert.SerializeObject(
new
{
jsonCreditApplication = customer
});
所以 jsonCreditApplication
变量将是:
{
"jsonCreditApplication": {
"gors_descr": "Appliances",
"b_name_first": "Marisol",
"b_name_last": "Testcase"
}
}
关于c# - 将 C# 对象转换为 Json 对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34862072/