将JObject转换为匿名类型

时间:2019-12-30 04:49:36

标签: c# json linq elasticsearch

我有一个JObject,并且想要将该JObject格式化为Object。我的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字符串不会每次都相同。每次都会改变。我可以针对这种情况动态创建对象吗?

1 个答案:

答案 0 :(得分:0)

请注意,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"
}
相关问题