c# - 将 C# 对象转换为 Json 对象

标签 c# json api serialization

我正在尝试将 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 序列化程序。例如DataContractJsonSerializerJson.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/

相关文章:

c# - 如何在C#项目中使用ZK4500指纹扫描仪SDK

java - 通过 REST 调用使用外键将项目添加到集合中

c# - 从 C# 中的 REST 服务下载文件

reactjs - 为什么 getDerivedStateFromProps() 被设计为静态

.net - 如何使用 .NET 创建 JSON 数据?

php - PHP 上的 Google Calendar API v3 域范围委托(delegate)服务帐户

c# - Entity Framework 中主键不递增

c# - 如何优化linq中的FirstOrDefault语句

c# - 从 Unity 中的另一个脚本调用 IEnumerator 方法并获取其返回值

javascript - 如何在 javascript 中编写解析器以使用模型将编辑器中的文本解析为 JSON?