将动态JSON对象传递给Web API - Newtonsoft示例

dav*_*avy 11 asp.net-mvc json asp.net-mvc-4 asp.net-web-api

我需要将动态JSON对象传递给我的Web API控制器,以便我可以根据它的类型来处理它.我尝试过使用可以在这里看到的JSON.NET示例但是当我使用Fiddler时,我可以看到传入的JObect总是为null.

这是粘贴到Fiddler中的一个例子:

POST http://localhost:9185/api/Auto/PostSavePage/  HTTP/1.1
User-Agent: Fiddler
Content-type: application/json
Host: localhost
Content-Length: 88

{AlbumName: "Dirty Deeds",Songs:[ { SongName: "Problem Child"},{ SongName:  
"Squealer"}]}
Run Code Online (Sandbox Code Playgroud)

这里的Ans是我非常简单的Web API控制器方法:

 [HttpPost]
 public JObject PostSavePage(JObject jObject)
 {        
     dynamic testObject = jObject;         
     // other stuff here
 }
Run Code Online (Sandbox Code Playgroud)

我是新手,我对这方面有几个问题:

我在这个特定的例子中做错了吗?

可以说,更重要的是,是否有更好的方法来传递动态JSON对象(来自JavaScript AJAX帖子)?

Mar*_*nes 14

根据Perception的评论,您的JSON看起来不合适.通过JSONLint运行它,你得到:

Parse error on line 1:
{    AlbumName: "Dirty De
-----^
Expecting 'STRING', '}'
Run Code Online (Sandbox Code Playgroud)

将其更改为"围绕字段名称:

{
    "AlbumName": "Dirty Deeds",
    "Songs": [
        {
            "SongName": "Problem Child"
        },
        {
            "SongName": "Squealer"
        }
    ]
}
Run Code Online (Sandbox Code Playgroud)

您是否尝试过替换JToken或动态对象的JObject(例如这里)?

[HttpPost]
 public JObject PostSavePage(JToken testObject)
 {                
     // other stuff here
 }
Run Code Online (Sandbox Code Playgroud)

要么

 [HttpPost]
 public JObject PostSavePage(dynamic testObject)
 {                
     // other stuff here
 }
Run Code Online (Sandbox Code Playgroud)


dav*_*avy 4

感谢所有在这里提供帮助的人。不幸的是,我从来没有弄清楚到底出了什么问题。

我将项目一点一点移植到一个新项目中,并且运行良好。

作为信息,我有一个 RouteConfig 类,目前非常简单:

public class RouteConfig
{       
    private static string ControllerAction = "ApiControllerAction";

    public static void RegisterRoutes(RouteCollection routes)
    {
        routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

        routes.MapHttpRoute(
            name: ControllerAction,
            routeTemplate: "api/{controller}/{action}/{id}",
            defaults: new { id = RouteParameter.Optional }
        );
    }
}
Run Code Online (Sandbox Code Playgroud)

我对 API 的调用现在使用 JSON.Stringify:

$.ajax("http://localhost:54997/api/values/PostSavePage/", {
    data:  JSON.stringify(jObject),                               
    contentType: 'application/json',
    type: 'POST'
});
Run Code Online (Sandbox Code Playgroud)

原始 API 操作有效。

请注意,我目前只是在玩这个,所以代码不是最好的,但我认为它在基本形式中可能有用,以防其他人遇到类似的问题。