0

I have a JObject and want to format that JObject to an Object. My JSON stirng is

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

I want this JSON string to be formatted as

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

How can we do this? My JSON string is not a strongly typed Object. But I want to convert that into this format. My Json string will not be of same at every time. It changes each time. Can I create an object dynamically for this scenario?

Uwe Keim
  • 39,551
  • 56
  • 175
  • 291
Ayyappa P
  • 3
  • 3
  • Sounds like an [XY problem](http://xyproblem.info/). – Uwe Keim Dec 30 '19 at 04:56
  • Could you use `ExpandoObject` as shown in [How to deserialize using JSON.Net to an anonymous type?](https://stackoverflow.com/q/7995856/3744182)? If not, truly creating an anonymous type object in runtime is very difficult, see [How to create LINQ Expression Tree to select an anonymous type](https://stackoverflow.com/q/606104/3744182). – dbc Dec 30 '19 at 05:02
  • Or are you looking for [Custom JSON Derivative Format](https://stackoverflow.com/q/30610196/3744182)? That question shows how to replace the `:` separator between JSON object keys and values with `=`. – dbc Dec 30 '19 at 05:15
  • I would go for QuoteName Property or something simple like that https://stackoverflow.com/questions/7553516/json-net-serialize-property-name-without-quotes – xdtTransform Dec 31 '19 at 09:45

1 Answers1

0

Please do note that JSONs are not formatted with =, instead with a :. You wont be able to deserialize it once its formatted with =.

You can do this,

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

Output

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

Printing Without Quotes on Keys

If you are interested in printing the Keys without quotes, you can run the following method. This method breaks each line and removes quotes from Each Key.

    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);

Output

{
  Prop1= "Prop1Value"
  Prop2= 1
  Prop3= "Prop3Value"
  dtProp= "2019-12-30T09=59=48"
}
Jawad
  • 11,028
  • 3
  • 24
  • 37