Json(JToken.Parse(response)) 返回空数组

问题描述 投票:0回答:2

我使用 HttpClient 来使用 API,然后我从 response.Content.ReadAsStringAsync().Result 获取序列化字符串形式的响应,如下所述,

"{\r\n  \"responseCode\": 400,\r\n  \"errors\": [\r\n    {\r\n      \"errorCode\": \"RPM400\",\r\n      \"errorMessage\": \"A program already exists.\"\r\n    }\r\n  ]\r\n}"

我想将其反序列化为

{
  "responseCode": 400,
  "errors": [
    {
      "errorCode": "RPM400",
      "errorMessage": "A program already exists."
    }
  ]
}

然后我必须将它发送到UI,ASP.Net MVC 5 ActionMethod 中的返回类型是ActionResult。

我尝试使用 Json(JObject.Parse(response)) 和 Json(JToken.Parse(response)) 但我在邮递员中得到空响应,如下

[
    [
        []
    ],
    [
        [
            [
                [
                    []
                ],
                [
                    []
                ]
            ]
        ]
    ]
]

相同的 Json(JObject.Parse(response)) 正在另一个应用程序 ASP.Net Core 2 中工作。您能提供一些帮助吗?

json asp.net-mvc-5
2个回答
0
投票

我已经使用了 stackOverflow's 标记的答案,我必须使用 using System.Web.Script.Serialization; 进行反序列化,然后它就起作用了,因为我的 .Net Framework 是 4.7.2


0
投票

这是因为JObject与所使用的序列化器不兼容。 但是经过数小时的努力你可以获得 MVC JsonResult 序列化

JObject.Parse(response).ToObject<Dictionary<string, object>>()
如果它是一个JObject并且如果它是一个JArray你需要
JObject.Parse(response).ToObject<List<Dictionary<string, object>>>()

© www.soinside.com 2019 - 2024. All rights reserved.