使用c#形成Json

时间:2015-10-01 11:43:11

标签: c# json asp.net-web-api

嗨我的json结构就像这样

{
  "OutputParam": [
    {
      "param1": "John",
      "param2": "Doe",
      "param3": "BT",
      "param4": [
        {
          "subparam1": "00002",
          "subparam2": "True",
          "subparam3": "-",
          "subparam4": "-",
          "subparam5": "data goes here"
        },
        {
          "subparam1": "00003",
          "subparam2": "True",
          "subparam3": "-",
          "subparam4": "-",
          "subparam5": "data goes here"
        },
        {
          "subparam1": "00004",
          "subparam2": "False",
          "subparam3": "111",
          "subparam4": "message",
          "subparam5": "-"
        }
      ]
    }
  ]
}

我从http://json2csharp.com/获得的课程如下

public class Param4
{
    public string subparam1 { get; set; }
    public string subparam2 { get; set; }
    public string subparam3 { get; set; }
    public string subparam4 { get; set; }
    public string subparam5 { get; set; }
}

public class OutputParam
{
    public string param1 { get; set; }
    public string param2 { get; set; }
    public string param3 { get; set; }
    public List<Param4> param4 { get; set; }
}

public class RootObject
{
    public List<OutputParam> OutputParam { get; set; }
}

现在问题是我想在c#API上传递Json作为API输出,我尝试了list和var但是到目前为止还没有能够返回上面提到的Json,可以任何一个帮助或者至少给出指示吗?

3 个答案:

答案 0 :(得分:1)

如果您想使用Web API按照示例返回

等方法
public RootObject GetRootObject()
{
   return new RootObject();
}

如果请求content negotiation中的API请求JSON,那么会这样做 - web api会将您的对象自动化为JSON

答案 1 :(得分:1)

以下是可以帮助您的小代码示例

public RootObject1 Get(int id)
    {
        RootObject1 rt = new RootObject1();
        OutputParam pr = new OutputParam();
        Param4 cr = new Param4();
        rt.OutputParam = new List<OutputParam>();
        pr.Param4= new List<Param4>();
        pr.Param1= "AB";
        rt.OutputParam = new List<OutputParam>();
        cr.Param6 = "aceee";
        pr.Param4.Add(cr);

        rt.OutputParam.Add(pr);
        return rt;
    }

答案 2 :(得分:0)

你的webservice c#prolly返回一个你的json作为字符串的xml?这是默认的

所以你有不同的选择

转到xml或将此行添加到您的方法

[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]