Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/ruby-on-rails/59.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 在C中向json序列化添加根元素#_C#_Json_Serialization_Json.net - Fatal编程技术网

C# 在C中向json序列化添加根元素#

C# 在C中向json序列化添加根元素#,c#,json,serialization,json.net,C#,Json,Serialization,Json.net,我正在创建一个与JSON API交互的Web服务 这个API需要我在字符串中设置一个根元素,但我无法实现这一点 这一切发生的地方——现在只是为了向我展示json输出: public static string CreateServiceChange(ServiceChange change) { string json = JsonConvert.SerializeObject(change); return json;

我正在创建一个与JSON API交互的Web服务

这个API需要我在字符串中设置一个根元素,但我无法实现这一点

这一切发生的地方——现在只是为了向我展示json输出:

public static string CreateServiceChange(ServiceChange change)
        {
            string json = JsonConvert.SerializeObject(change);

            return json;
        }
这是ServiceChange类:

public class ServiceChange
{
    [JsonProperty("email")]
    public string requesterEmail { get; set; }

    [JsonProperty("description_html")]
    public string descriptionHtml { get; set; }

    [JsonProperty("subject")]
    public string subject { get; set; }

    [JsonProperty("change_type")]
    public int changeType { get; set; }
}
以及将这两者结合在一起的方法:

    public string copyTicketToChange(int ticketId)
    {
        HelpdeskTicket.TicketResponseActual ticket = getHelpdeskTicket(ticketId);
        ServiceChange change = new ServiceChange();
        change.descriptionHtml = ticket.Response.DescriptionHtml;
        change.requesterEmail = ticket.Response.Email;
        change.subject = ticket.Response.Subject;
        change.changeType = 1;
        string Response = Dal.CreateServiceChange(change);
        return Response;
    }
json输出现在如下所示:

{"email":"test@test.com","description_html":"This is a test","subject":"Testing","change_type":1}
以及预期产量:

{ "itil_change": {"email":"test@test.com","description_html":"This is a test","subject":"Testing","change_type":1}}

如何实现这一点?

将您的ServiceChange包装到另一个对象中并序列化它:

  public class ServiceChangeWrapper
  {
    public ServiceChange itil_change { get; set; }
  }


工作完美!而且很简单!
public static string CreateServiceChange(ServiceChange change)
    {
        ServiceChangeWrapper wrapper = new ServiceChangeWrapper { itil_change = change};
        string json = JsonConvert.SerializeObject(wrapper);

        return json;
    }