【问题标题】:how to pass Json array in string - webapi in asp如何在字符串中传递Json数组-asp中的webapi
【发布时间】:2011-11-15 22:43:09
【问题描述】:

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

【问题讨论】:

  • 现在您的 Json 似乎无效。您可以使用jsonlint.com 对其进行测试
  • 我在jsonlint.com/,it 中测试显示“有效的Json”。
  • 好的,但是你的问题搞砸了。请在那里修复它,以便其他人可以轻松地测试它以帮助您。

标签: json wcf-web-api


【解决方案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);
}

你已经完成了这个方法。

另一种方法是使用 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);
}

【讨论】:

  • 多么棒的答案。当我的想法快要枯竭时,你救了我。
猜你喜欢
  • 2016-03-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-11-22
  • 1970-01-01
  • 1970-01-01
  • 2023-02-01
  • 2013-02-21
相关资源
最近更新 更多