3

私はそのメソッドでpostメソッドを使用しています。このようにJson全体を文字列で渡したい

{Data:" JsonArray"} in Jssonarray この値を渡したい

{   "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

1つの方法は、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);
}

そして、あなたはこの方法で終わりです。

もう1つの方法は、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 に答える