将 C# 对象转换为 Json 对象 [英] Convert C# Object to Json Object
问题描述
我正在尝试将 C# 对象序列化为 Json 对象.然后将其提交给 Salesforce API,并创建一个应用程序.现在我将 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.
这是我的 C# 对象以及随附的序列化.
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;
我需要在 JSON 对象中输出 JSON 字符串.我需要的一个例子如下:
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\", " +
"}";
这个硬编码的 json 字符串位于对象内部.目前,C# 对象中的值被输出到一个 JSON 字符串中,但我需要将它输出到一个对象中,以便 Salesforce API 接受提交.
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.
如何将 JSON 字符串附加或插入到对象中?
How can I append or insert the JSON string into an object?
推荐答案
要创建正确的 JSON,首先需要准备合适的模型.它可以是这样的:
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; }
}
为了能够使用 Data
属性,您需要选择其他一些 JSON 序列化程序.例如 DataContractJsonSerializer 或 Json.NET(我将在本例中使用它).
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
});
所以 jsonCreditApplication
变量将是:
{
"jsonCreditApplication": {
"gors_descr": "Appliances",
"b_name_first": "Marisol",
"b_name_last": "Testcase"
}
}
这篇关于将 C# 对象转换为 Json 对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!