【问题标题】:Convert C# Object to Json Object将 C# 对象转换为 Json 对象
【发布时间】:2016-04-24 01:22:55
【问题描述】:

我正在尝试将 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 字符串有效,您实际上可以使用此站点将 json 字符串转换为 C# 类 json2csharp.com 也可以查看指向 convert C# Object into Json 的链接
  • 首先,当您序列化application 时,您将获得类似于:{"ProductDescription": "gors_descr Appliances", "Fname": "b_name_first Marisol", ...} 的 JSON。它看起来不像你想要的 JSON。

标签: c# json api serialization


【解决方案1】:

要首先创建正确的 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"
  }
}

【讨论】:

    【解决方案2】:

    另一种方式。

    using System;
    using Newtonsoft.Json;
    
    namespace MyNamepace
    {
        public class MyCustomObject
        {
            public MyCustomObject()
            {
            }
    
            [JsonProperty(PropertyName = "my_int_one")]
            public int MyIntOne { get; set; }
    
            [JsonProperty(PropertyName = "my_bool_one")]
            public bool MyBoolOne { get; set; }
    
        }
    }
    

            /* using Newtonsoft.Json; */
    
            MyCustomObject myobj = MyCustomObject();
            myobj.MyIntOne = 123;
            myobj.MyBoolOne = false;
    
            string jsonString = JsonConvert.SerializeObject(
                myobj,
                Formatting.None,
                new JsonSerializerSettings()
                {
                    ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore
                });
    

    http://www.newtonsoft.com/json/help/html/T_Newtonsoft_Json_JsonSerializerSettings.htm

    我在撰写本文时的 packages.config...虽然我确信未来/最新版本仍会支持它:

    <?xml version="1.0" encoding="utf-8"?>
    <packages>
      <package id="Newtonsoft.Json" version="6.0.8" targetFramework="net45" />
    </packages>
    

    【讨论】:

    • +1 用于使用 Newonsoft 解决方案 - 请记住,要使用它,您需要使用 NuGet 包管理器安装它的包,并且(当然)在“使用”部分包含 Newtonsoft.Json 跨度>
    • 嘿。感谢您的反馈。我添加了 packages.config。 “使用”已经存在! :)
    【解决方案3】:
    using System; 
    using Newtonsoft.Json; 
    using Newtonsoft.Json.Linq;
    
    CurrentUTCDateTime yourObject = new CurrentUTCDateTime(); 
    JObject json = JObject.Parse(JsonConvert.SerializeObject(yourObject));
    

    【讨论】:

    • 欢迎来到 StackOverflow!请提供一些解释,为什么您认为您提出的解决方案可能对 OP 有所帮助。
    • 我的解决方案会帮助那些想要从对象中获取 json 作为 JsonObject 的人
    • 欢迎来到 Stack Overflow。 Stack Overflow 上不鼓励仅使用代码的答案,因为它们没有解释它是如何解决问题的。请编辑您的答案以解释此代码的作用以及它如何回答问题,以便它对 OP 以及其他有类似问题的用户有用。
    【解决方案4】:

    安装Newtonsoft.Json NuGet 然后用需要的命名装饰来装饰客户类,以告诉 Json 序列化程序如何序列化客户类字段:

    public class Customer
    {
        [JsonProperty("gors_descr")]
        public string ProductDescription;
        [JsonProperty("b_name_first")]
        public string Fname;
        [JsonProperty("b_name_last")]
        public string Lname;
    }
    

    接下来,像这样序列化对象:

    Customer application = new Customer
            {
                ProductDescription = "Appliances ",
                Fname = "Marisol ",
                Lname = "Testcase "
    
            };
            var JsonOutput = JsonConvert.SerializeObject(new { jsonCreditApplication = application });
    

    您将获得所需的结果,JsonOutput 的值将是: "{\"jsonCreditApplication\":{\"gors_descr\":\"Appliances \",\"b_name_first\":\"Marisol \",\"b_name_last\":\"Testcase \"}}"

    有很多方法可以做到这一点,但我相信这是最简单的解决方案。

    【讨论】:

      【解决方案5】:

      您可以使用 http://restsharp.org/ 之类的东西,这是一个用于 REST 的 c# 库。如果是这样,它有一个内置的 json 对象序列化器 (.addJsonBody()) 或者你可以自己序列化它并添加

          request.AddParameter("application/json; charset=utf-8", json, ParameterType.RequestBody);
      

      或者,如果您想对其进行更多控制,您可以使用

          System.Net.HttpWebRequest()
      

      我也找到了https://github.com/ademargomes/JsonRequest,但它仍在开发中。 请注意,如果您使用 RestSharp 之类的东西,它是一个固定请求,因此与他们创建的标准请求(例如,带 json 或自定义标头甚至自定义身份验证的多部分/表单数据)的任何变化都可能无法与他们的库一起使用,在这种情况下,最好还是使用 HttpWebRequest 自己制作。希望对您有所帮助!

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-11-02
        • 1970-01-01
        • 2011-11-27
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多