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

时间:2022-09-15 11:58:00

I need to pass a dynamic JSON object to my Web API controller so that I can process it depending on what type it is. I have tried using the JSON.NET example that can be seen here but when I use Fiddler, I can see that the passed in JObect is always null.

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

This is an exert from the example pasted into Fiddler:

这是粘贴到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"}]}

Ans here is my very simple Web API controller method:

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

 [HttpPost]
 public JObject PostSavePage(JObject jObject)
 {        
     dynamic testObject = jObject;         
     // other stuff here
 }

I am new to this and I have a couple of questions around this area:

我是新手,在这个领域我有几个问题:

Am I doing something wrong in this particular example?

在这个例子中我做错了什么吗?

Arguably, more importantly, is there a better way to pass in a dynamic JSON object (from an JavaScript AJAX post)?

可以说,更重要的是,是否有更好的方式传入动态JSON对象(来自JavaScript AJAX post)?

2 个解决方案

#1


14  

As per Perception's comment your JSON doesn't look valid. Run it through JSONLint and you get:

根据感知的评论,您的JSON看起来不正确。通过JSONLint运行它,你得到:

Parse error on line 1:
{    AlbumName: "Dirty De
-----^
Expecting 'STRING', '}'

Change it to have " around the field names:

将其更改为“围绕字段名:

{
    "AlbumName": "Dirty Deeds",
    "Songs": [
        {
            "SongName": "Problem Child"
        },
        {
            "SongName": "Squealer"
        }
    ]
}

Also have you tried swapping out your JObject for either a JToken or a Dynamic object (e.g. here)?

您是否尝试过将JObject替换为JToken或Dynamic对象(例如这里)?

[HttpPost]
 public JObject PostSavePage(JToken testObject)
 {                
     // other stuff here
 }

OR

 [HttpPost]
 public JObject PostSavePage(dynamic testObject)
 {                
     // other stuff here
 }

#2


3  

Thanks to everyone who helped here. Unfortunately, I never got to the bottom of what was wrong.

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

I ported the project over piece by piece to a new project and it works fine.

我把这个项目一件件地移植到一个新项目上,效果很好。

For info, I have a RouteConfig class, which is quite simple at the moment:

关于信息,我有一个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 }
        );
    }
}

My call into the API now uses JSON.Stringify:

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

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

The original API action works.

最初的API动作有效。

Note, that I'm only playing with this at the moment so the code is not the best but I thought it may be useful in basic form in case someone else has a similar issue.

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

#1


14  

As per Perception's comment your JSON doesn't look valid. Run it through JSONLint and you get:

根据感知的评论,您的JSON看起来不正确。通过JSONLint运行它,你得到:

Parse error on line 1:
{    AlbumName: "Dirty De
-----^
Expecting 'STRING', '}'

Change it to have " around the field names:

将其更改为“围绕字段名:

{
    "AlbumName": "Dirty Deeds",
    "Songs": [
        {
            "SongName": "Problem Child"
        },
        {
            "SongName": "Squealer"
        }
    ]
}

Also have you tried swapping out your JObject for either a JToken or a Dynamic object (e.g. here)?

您是否尝试过将JObject替换为JToken或Dynamic对象(例如这里)?

[HttpPost]
 public JObject PostSavePage(JToken testObject)
 {                
     // other stuff here
 }

OR

 [HttpPost]
 public JObject PostSavePage(dynamic testObject)
 {                
     // other stuff here
 }

#2


3  

Thanks to everyone who helped here. Unfortunately, I never got to the bottom of what was wrong.

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

I ported the project over piece by piece to a new project and it works fine.

我把这个项目一件件地移植到一个新项目上,效果很好。

For info, I have a RouteConfig class, which is quite simple at the moment:

关于信息,我有一个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 }
        );
    }
}

My call into the API now uses JSON.Stringify:

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

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

The original API action works.

最初的API动作有效。

Note, that I'm only playing with this at the moment so the code is not the best but I thought it may be useful in basic form in case someone else has a similar issue.

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