问题
I am using post method in that method i want to pass entire Json in string like this way
{Data:" JsonArray"} in Jssonarray I want to pass this value
{ "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" }
]
}
When i pass this I am getting 500 internal Error
Please help me how to pass Entire Json in a single string.
回答1:
One way is to navigate to http://json2csharp.com/, paste your Json and hit "GO".
The result will be this one (I fixed the capitalization):
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; }
}
Paste this into your application.
Your POST-Method then could look like this:
[WebInvoke(Method = "POST", UriTemplate = "")]
public HttpResponseMessage Add(RootObject root) {
// do something with your root objects or its child objects...
return new HttpResponseMessage(HttpStatusCode.Created);
}
And you're done with this method.
Another method is to use the new JsonValue and JsonArray introduced with Web API whereas you don't need RootObject and Result.
Just use your POST-Method:
[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);
}
You should get a clue...
You can prettify the whole thing:
[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);
}
来源:https://stackoverflow.com/questions/8135587/how-to-pass-json-array-in-string-webapi-in-asp