【问题标题】:Generate JSON structure [duplicate]生成 JSON 结构 [重复]
【发布时间】:2019-07-28 23:10:26
【问题描述】:

我正在尝试在我的代码 (C#) 中创建以下 JSON 结果,因为这是我使用的 API 希望 JSON 的样子,但无法准确创建它,因此这就是 API 返回的原因有错误。

最终结果:

{
  "reportKey" : {
     "key" : "552d20ce-1269-4cb4-a679-0cd51d3e2058"
  }
}

在我的代码中,我有

var reportKey = new KeyValuePair<string, string>("key", reportId);
var requestJson = new { reportKey };

当我通过使用JsonConvert 序列化这个requestJson 来查找JSON 值时,它会出现

{ reportKey : { key : "key", value : "CBHJ1234" } } 

不是我想要的方式。

关于我可能做错的任何想法?我可能不想在这里使用KeyValuePair,对吧?

【问题讨论】:

  • 用字典怎么样

标签: c# json


【解决方案1】:

具有讽刺意味的是,KeyValuePair 在序列化为 JSON 时会创建两个键值对,因为它有两个属性 KeyValue

最简单的方法是不使用KeyValuePair,自己创建一个匿名类:

var objectToSerialise = new {
    reportKey = new {
        key = reportId
    }
};

var json = JsonConvert.SerializeObject(objectToSerialise);

【讨论】:

    猜你喜欢
    • 2022-09-28
    • 2013-03-29
    • 1970-01-01
    • 1970-01-01
    • 2023-04-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-01-22
    相关资源
    最近更新 更多