【问题标题】:Invalid JSON string, cannot post to c# web api?无效的 JSON 字符串,无法发布到 c# web api?
【发布时间】:2013-10-24 14:36:03
【问题描述】:

我得到了这个 JSON 字符串,它有什么问题?我可以通过几个在线 JSON 测试器运行它,他们都说 OK。但是,当它通过实体框架发布到我的 c# web api 时,我的帖子正文为空。有任何想法吗? 这是 POST 函数:

public void Post([FromBody]List<AIM.RunningProcess> list_runningprocesses)
{
    if (list_runningprocesses == null) return;

这是 JSON 字符串:

[
    {
      "PSComputerName":  "eetpcx31v.admin.eetp.local",
      "ProcessName":  "AcroRd32.exe",
      "ProcessID":  14240,
      "CommandLine":  ".C:\\Program Files (x86)\\Adobe\\Reader 10.0\\Reader\\AcroRd32.exe. .C:\\Users\\jmetzler\\AppData\\Local\\Microsoft\\Windows\\Temporary Internet Files\\Content.Outlook\\VG2QRLL8\\Pöyry_RevealingFlexibilityValueStudy_Proposal_v2_0.pdf.",
      "CreationDate":  "Oct 24 2013 14:21:09",
      "Username":  "jmetzler",
      "RemoteIP":  null
    }
]

显然由于 CommandLine 属性而失败。 “命令行”的数据库列属性是 varchar(8000)。这是“RunningProcess”类。

public partial class RunningProcess
{
    public string PSComputerName { get; set; }
    public string ProcessName { get; set; }
    public string ProcessID { get; set; }
    public string CommandLine { get; set; }
    public Nullable<System.DateTime> CreationDate { get; set; }
    public string Username { get; set; }
    public string RemoteIP { get; set; }
}

有人知道吗?

【问题讨论】:

  • JsonConvert.DeserializeObject&lt;List&lt;RunningProcess&gt;&gt;(json) 为我工作(json 是您的 JSON 字符串)。为什么说“显然由于 CommandLine 属性而失败”?我看不出有什么明显的错误。

标签: c# json entity-framework asp.net-web-api


【解决方案1】:

使用http://json2csharp.com/ 生成您的 C# 类。答案中的类是从同一站点生成的。

从 JSON 你的类应该是这样的:

public class RootObject
{
    public string PSComputerName { get; set; }
    public string ProcessName { get; set; }
    public int ProcessID { get; set; }
    public string CommandLine { get; set; }
    public DateTime CreationDate { get; set; }
    public string Username { get; set; }
    public string RemoteIP { get; set; }
}

因为您的ProcessIDint

【讨论】:

  • 您还将CreationDate 更改为stringRemoteIP 更改为object。我认为这些都是不必要和不受欢迎的变化。
  • @TimS.,你说得对,我只是从生成的代码中忽略了这些。
【解决方案2】:

如果我正确解决了您的问题,请尝试将 JSON 字符串更改为:

{list_runningprocesses:
[
{
  "PSComputerName":  "eetpcx31v.admin.eetp.local",
  "ProcessName":  "AcroRd32.exe",
  "ProcessID":  14240,
  "CommandLine":  ".C:\\Program Files (x86)\\Adobe\\Reader 10.0\\Reader\\AcroRd32.exe. .C:\\Users\\jmetzler\\AppData\\Local\\Microsoft\\Windows\\Temporary Internet Files\\Content.Outlook\\VG2QRLL8\\Pöyry_RevealingFlexibilityValueStudy_Proposal_v2_0.pdf.",
  "CreationDate":  "Oct 24 2013 14:21:09",
  "Username":  "jmetzler",
  "RemoteIP":  null
 }
]
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-08-02
    • 1970-01-01
    • 2016-02-17
    • 1970-01-01
    • 2019-05-10
    • 2018-01-25
    • 2017-09-10
    • 2012-12-21
    相关资源
    最近更新 更多