简体   繁体   中英

Serialize C# class into nested JSON with specified paths in JsonProperty attribute

I have flat C# class with lots of properties and I want to serialize an instance of that class into JSON using Json.NET. While serializing, I need to produce a JSON string that is nested. I know that I can create subclasses to achieve this but this is unnecessary overhead.

Let's assume I have this class:

public class MyClass{
  [JsonProperty("subgroupa.myotherproperty")]
  public int MyProperty {get;set;} = 5;
}

How can I get this JSON:

{
  "subgroupa": {
     "myotherproperty": 5
   }
}

In the past, I was able to deserialize such a nested JSON string into a flat object. Therefore, I believe Json.NET can also do the opposite.

    using System.Text.Json; 

    public class MyClass{
        [JsonProperty("subgroupa.myotherproperty")]
        public int MyProperty {get;set;} = 5;}

  string subgroupa = JsonSerializer.Serialize(MyClass);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM