如何在字符串中传递Json数组-ASP中的WebAPI [英] how to pass Json array in string - webapi in asp

查看:132
本文介绍了如何在字符串中传递Json数组-ASP中的WebAPI的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在该方法中使用post方法,我想像这样通过字符串传递整个Json

I am using post method in that method i want to pass entire Json in string like this way

我要传递此值的Jssonarray中的{Data:"JsonArray"}

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

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

When i pass this I am getting 500 internal Error
Please help me how to pass Entire Json in a single string.

推荐答案

一种方法是导航到 http://json2csharp.com/ ,粘贴您的Json并点击"GO".

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.

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

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);
}

您已完成此方法.

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

Another method is to use the new JsonValue and JsonArray introduced with Web API whereas you don't need RootObject and Result.

只需使用您的POST方法:

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...

您可以美化整件事:

[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);
}

这篇关于如何在字符串中传递Json数组-ASP中的WebAPI的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆