Frederik
Frederik

Reputation: 652

Add root element to json serialization in C#

I am creating a webservice to interact with a JSON API.

This API needs me to set a root element in the string, but I just cannot get this to happen.

The place where it all happens - right now just made to just show me the json output:

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

            return json;
        }

This is the ServiceChange class:

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; }
}

And the method binding those two together:

    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;
    }

The json output looks like this right now:

{"email":"[email protected]","description_html":"This is a test","subject":"Testing","change_type":1}

And the expected output:

{ "itil_change": {"email":"[email protected]","description_html":"This is a test","subject":"Testing","change_type":1}}

How can I achieve this?

Upvotes: 1

Views: 4297

Answers (1)

Crowcoder
Crowcoder

Reputation: 11514

Wrap your ServiceChange into another object and serialize it:

  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;
    }

Upvotes: 3

Related Questions