我正在创建一个与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}}
我怎样才能做到这一点?
答案 0 :(得分: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;
}