将C#对象转换为Json对象

12

我正试图将一个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 字符串转换为对象?https://dev59.com/fHVD5IYBdhLWcg3wO5AD?rq=1 - stuartd
首先确保您的json字符串是有效的,您可以使用此网站将json字符串转换为C#类http://json2csharp.com/,还可以查看此链接以将C#对象转换为Json:https://dev59.com/questions/Tm025IYBdhLWcg3wIyKf。 - MethodMan
首先,当您序列化“应用程序”时,您将获得类似于以下内容的JSON:“{"ProductDescription": "gors_descr Appliances", "Fname": "b_name_first Marisol", ...}”。它看起来不像您想要的JSON。 - Aleksandr Ivanov
5个回答

20

为了创建正确的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"
  }
}

3
using System; 
using Newtonsoft.Json; 
using Newtonsoft.Json.Linq;

CurrentUTCDateTime yourObject = new CurrentUTCDateTime(); 
JObject json = JObject.Parse(JsonConvert.SerializeObject(yourObject));

3
欢迎来到StackOverflow!请提供一些解释,为什么你认为你提出的解决方案可能会帮助提问者。 - Peter Csala
1
我的解决方案将有助于那些想要从对象中获取JSON作为JsonObject的人。 - Md. Foyjul Bary
欢迎来到 Stack Overflow。在 Stack Overflow 上,我们不鼓励仅包含代码的回答,因为它们未能解释代码如何解决问题。请编辑您的回答,解释代码的作用和如何解决问题,这样对提问者和其他有类似问题的用户都有用。 - FluffyKitten

2

安装Newtonsoft.Json NuGet,然后为Customer类添加必需的命名修饰符,以告诉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\":\"家电 \",\"b_name_first\":\"Marisol \",\"b_name_last\":\"测试用例 \"}}"
有很多方法可以实现这个目标,但我认为这是最简单的解决方案。

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包管理器安装其软件包,并在“using”部分中包含Newtonsoft.Json(当然)。 - Thomas Hansen
1
嘿,谢谢反馈。我已经添加了packages.config文件。"using"语句已经存在了! :) - granadaCoder

0
你可以使用类似 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自己创建。希望能帮到你!

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接