将C#对象转换为Json对象

Mow*_*ite 8 c# api serialization json

我试图将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;
Run Code Online (Sandbox Code Playgroud)

我需要在JSON对象内输出JSON字符串.我需要的一个例子如下:

"{ \"jsonCreditApplication\" : " +
    "\"gors_descr\" : \"Appliances\", " +
    "\"b_name_first\" : \"Marisol\", " +
    "\"b_name_last\" : \"Testcase\", " +
"}"; 
Run Code Online (Sandbox Code Playgroud)

此硬编码的json字符串位于对象内部.按照目前的情况,C#对象中的值将输出到JSON字符串中,但我需要将其输出到对象中,以便Salesforce API接受提交.

如何将JSON字符串追加或插入对象?

Ale*_*nov 17

要首先创建正确的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; }
}
Run Code Online (Sandbox Code Playgroud)

为了能够使用Data属性,您需要选择其他一些JSON序列化程序.例如DataContractJsonSerializerJson.NET(我将在本例中使用它).

Customer customer = new Customer
{
    ProductDescription = tbDescription.Text,
    Fname = tbFName.Text,
    Lname = tbLName.Text
};


string creditApplicationJson = JsonConvert.SerializeObject(
    new
    {
        jsonCreditApplication = customer
    });
Run Code Online (Sandbox Code Playgroud)

所以jsonCreditApplication变量将是:

{
  "jsonCreditApplication": {
    "gors_descr": "Appliances",
    "b_name_first": "Marisol",
    "b_name_last": "Testcase"
  }
}
Run Code Online (Sandbox Code Playgroud)