从C#Web Service自定义JSON输出

时间:2017-10-17 01:13:33

标签: c# json web-services

我有来自C#Web服务的以下输出:

{"CallResult":[{"CompanyId":"AAA900134-904","CompanyName":"MID"}]}

我希望输出只包含一个JSON数组,如下所示:

[{"CompanyId":"AAA900134-904","CompanyName":"MID"}]

我不确定如何自定义输出。我是否必须返回字符串并手动自定义JSON还是有其他方法吗?谢谢。

2 个答案:

答案 0 :(得分:0)

没有更多信息,例如实际数据示例(此json仅指1个对象),我可以建议:

创建2个自定义类,如下所示:

print("\tThis script is to erase and rewrite files")
filename = input("Filename: ")

print(f"\tWe're going to erase {filename}, then rewrite it.\n")
input("To cancel press CTRL-C\nTo continue press RETURN")

with open(filename, "w") as target:
  print("Opening the file...")
  print("Erasing the file. Goodbye!\n")
  target.truncate()
  rewrite = input("Time to rewrite your file, when you're finished   press RETURN:\n ")
   target.write(rewrite)

print("\n\tRewrite Confirmation:\n")
with open(filename) as this:
   print('> ', this.read(), '\n')
   if this == rewrite:
      print("Rewrite complete.")
   else:
      print("Rewrite failed. Please try again.")

然后,与public class CallResultClass { public List<InnerClass> CallResult { get; set; } } public class InnerClass { public string CompanyId { get; set; } public string CompanyName { get; set; } } 一起,您可以按如下方式反序列化json:

using System.Web.Script.Serialization;

如果您的json包含CallResults列表,则对代码的简单修改可以适应这种情况。没有修改json字符串的可能性(总是有一种干净的方式)。

供参考&amp;示例阅读JavaScriptSerializer Class

答案 1 :(得分:0)

我找到了解决方案。

[WebInvoke(Method = "GET",
        ResponseFormat = WebMessageFormat.Json,
        BodyStyle = WebMessageBodyStyle.Bare,
        UriTemplate = "/CallResult/{username}/{company}")]
    CallResult_Result[] CallResult(string username, string company);

我不得不改变

BodyStyle = WebMessageBodyStyle.Wrapped 

BodyStyle = WebMessageBodyStyle.Bare