【问题标题】:create json structure for in wcf(dynamic key for json)在 wcf 中创建 json 结构(json 的动态键)
【发布时间】:2018-08-21 09:42:46
【问题描述】:

如何使用类声明动态键?

{
"balls": {"a8bf081d-eaef-44db-ba25-97ed8c0b30ef": {"team": {"runs": 1,
          "extras": 0,
          "ball_count": 1,
          "wicket": 0
        }
      },
}}

【问题讨论】:

  • 你应该给你的 Json 和对象一个更好的定义。因为他不是有效的Json。您发布的第一个代码和这个代码之间有很多区别。最简单的方法是使用Dictionary<string, myCustomObj> Foos
  • 如果你对一个有效的 json 进行了反序列化,反过来搜索你会发现很容易对这些对象进行序列化。

标签: c# .net wcf


【解决方案1】:

根据您最后的 Json 格式,仍然无效但接近。 你有以下课程

public class Team
{
    public int runs { get; set; }
    public int extras { get; set; }
    public int ball_count { get; set; }
    public int wicket { get; set; }
}

使用Dictionary<string, Team>,您可以简单地:

var objFoo = new
{
    balls = new Dictionary<string, Team>
    {
        {
            "a8bf081d-eaef-44db-ba25-97ed8c0b30ef",
            new Team{
                runs=1,
                extras=0,
                ball_count=1,
                wicket=0
            }
        }
    }
};

var result = JsonConvert.SerializeObject(objFoo);

online Exemple

【讨论】:

    猜你喜欢
    • 2010-12-16
    • 1970-01-01
    • 2017-12-27
    • 1970-01-01
    • 2020-08-23
    • 2023-04-06
    • 2016-07-25
    • 2017-06-27
    • 1970-01-01
    相关资源
    最近更新 更多