3

我在该方法中使用 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。

4

1 回答 1

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);
}
于 2011-11-15T13:15:15.487 回答