1

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?

1 Answer 1

3

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;
    }
Sign up to request clarification or add additional context in comments.

1 Comment

Works perfect! And simple!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.