c# - 将JObject转换为匿名类型

标签 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字符串不会每次都相同。每次都会改变。我可以针对这种情况动态创建对象吗?

最佳答案

请注意,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"
}

关于c# - 将JObject转换为匿名类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59525848/

相关文章:

javascript - Node js : access json if variable name in string?

c# - 双重分组为 Dictionary<int, Dictionary<string, List<Model>>>()

c# - 用于选择畅销书的 LINQ 查询

c# - XPATHS 和默认命名空间

c# - 使用 DataContractSerializer 反序列化对象中的 XML

c# - 从流阅读器中删除最后 x 行

php - 查询返回 3 行的相同数据

javascript - 拆分每个字段中的ajax json响应错误

c# - System.Data.DataTable、DataRowCollection 和 DataColumns : How does the indexing work?

C# Linq .ToDictionary() 键已存在