【问题标题】:Converting a JObject to an Anonymous type将 JObject 转换为匿名类型
【发布时间】:2020-04-18 21:43:53
【问题描述】:

我有一个 JObject 并且想将该 JObject 格式化为一个对象。我的 JSON 搅拌是

{"Prop1":"Prop1Value","Prop2":1,"Prop3":"Prop3Value","dtProp":"2019-12-30T09:59:48"}

我希望这个 JSON 字符串被格式化为

{
    Prop1 = "Prop1Value",
    Prop2 = 1,
    Prop3 = "Prop3Value",
    dtProp = "2019-12-30T09:59:48"
} 

我们怎样才能做到这一点?我的 JSON 字符串不是强类型对象。但我想把它转换成这种格式。我的 Json 字符串每次都不相同。它每次都在变化。我可以为这种情况动态创建一个对象吗?

【问题讨论】:

标签: c# json linq elasticsearch


【解决方案1】:

请注意,JSON 的格式不是=,而是:。一旦格式化为=,您将无法对其进行反序列化。

你可以这样做,

  string newFormatted = JsonConvert.SerializeObject(JObject.Parse(json), Formatting.Indented).Replace(":", "=");
  Console.WriteLine(newFormatted);

输出

{
  "Prop1"= "Prop1Value",
  "Prop2"= 1,
  "Prop3"= "Prop3Value",
  "dtProp"= "2019-12-30T09=59=48"
}

在按键上不带引号打印

如果您有兴趣打印不带引号的密钥,可以运行以下方法。此方法会中断每一行并从每个键中删除引号。

    string str = JsonConvert.SerializeObject(JObject.Parse(json), Formatting.Indented);
    string newStr = string.Empty;
    str.Split(Environment.NewLine).ToList().ForEach(line => newStr += string.Join("=", line.Split(':').Select((x, index) => index % 2 == 0 ? x.Replace(@"""", "") : x)) + Environment.NewLine);

输出

{
  Prop1= "Prop1Value"
  Prop2= 1
  Prop3= "Prop3Value"
  dtProp= "2019-12-30T09=59=48"
}

【讨论】:

  • OP 想要围绕值的引号在哪里?
  • 是的,我不想要输出中的引号。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2012-05-01
  • 2012-01-20
  • 1970-01-01
  • 2010-11-27
  • 2011-04-19
  • 1970-01-01
相关资源
最近更新 更多