如何在字符串中传递Json数组 - 在asp中使用web api

时间:2011-11-15 11:22:46

标签: json wcf-web-api

我在该方法中使用post方法我想以这种方式将整个Json传递给字符串

Jssonarray中的

{Data:“JsonArray”}我想传递这个值

{   "version" : 2,
"query" : "Companies, CA",
"begin" : 1,
"end" : 3,
"totalResults" : 718,
"pageNumber" : 0,

"results" : [ 
      { "company" : "ABC Company Inc.",  "city" : "Sacramento",  "state" : "CA" } ,
      { "company" : "XYZ Company Inc.",  "city" : "San Francisco",  "state" : "CA" } ,
      { "company" : "KLM Company Inc.",  "city" : "Los Angeles",  "state" : "CA" } 
]
}

当我通过此操作时,我收到 500内部错误
 请帮我讲述如何在一个字符串中传递整个Json。

1 个答案:

答案 0 :(得分:5)

一种方法是导航到http://json2csharp.com/,粘贴你的Json并点击“GO”。

结果将是这一个(我修正了大写):

public class Result {
    public string Company { get; set; }
    public string City { get; set; }
    public string State { get; set; }
}

public class RootObject {
    public int Version { get; set; }
    public string Query { get; set; }
    public int Begin { get; set; }
    public int End { get; set; }
    public int TotalResults { get; set; }
    public int PageNumber { get; set; }
    public Result[] Results { get; set; }
}

将其粘贴到您的应用程序中。

您的POST方法可能如下所示:

[WebInvoke(Method = "POST", UriTemplate = "")]
public HttpResponseMessage Add(RootObject root) {

    // do something with your root objects or its child objects...

    return new HttpResponseMessage(HttpStatusCode.Created);
}

你完成了这个方法。

另一种方法是使用Web API引入的新JsonValue和JsonArray,而不需要RootObject和Result。

只需使用你的POST方法:

[WebInvoke(Method = "POST", UriTemplate = "")]
public HttpResponseMessage Add(JsonValue json) {
    JsonArray arr = (JsonArray) json["results"];
    JsonValue result1 = arr[0];
    var company = result1["company"]; // results in "ABC Company Inc."
    return new HttpResponseMessage(HttpStatusCode.Created);
}

你应该得到一个线索......

你可以美化整个事情:

[WebInvoke(Method = "POST", UriTemplate = "")]
public HttpResponseMessage Add(JsonValue json) {
    var arr = json["results"];
    var result1 = arr[0];
    var company = result1["company"]; // results in "ABC Company Inc."
    return new HttpResponseMessage(HttpStatusCode.Created);
}