Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

145
Views
What is the proper way to wrap a JSON object in another object?

I have run into this problem before, where I create a data model that will later be serialized into a JSON string, but I want the class containing the properties to also be serialized. See the example below:

I have my data model:

public class MyModel
{
    [JsonProperty(PropertyName = "Prop1")]
    public string Property1 { get; set; }

    [JsonProperty(PropertyName = "Prop2")]
    public string Property2 { get; set; }
}

Which would then serialize to:

{
    "Prop1":"Some Value",
    "Prop2":"Some Value"
}

Is there a way I can make it serialize to:

{
    "MyModel":
    {
        "Prop1":"Some Value",
        "Prop2":"Some Value"
    }
}

What I am currently doing which does not seem proper at all is something like this to create a wrapping object for my JSON:

string object = @"{""ticket"":" + JsonConvert.SerializeObject(model) + @"}"

Is there some kind of attribute I can add to my class something like:

[SerializeThisClass, ProperName="MyModel"]
public class MyModel
{
    [JsonProperty(PropertyName = "Prop1")]
    public string Property1 { get; set; }

    [JsonProperty(PropertyName = "Prop2")]
    public string Property2 { get; set; }
}
over 4 years ago · Santiago Trujillo
3 answers
Answer question

0

JsonConvert.SerializeObject( new{ MyModel = model})

should be ok

over 4 years ago · Santiago Trujillo Report

0

Add another class that has MyModel as its member then serialize the parent.

public class Parent
{
    [JsonProperty(PropertyName = "MyModel")]
    public MyModel MyModel { get; set; }

}
over 4 years ago · Santiago Trujillo Report

0

you may achieve that with this

 public class MyModel
 {
      [JsonProperty(PropertyName = "Prop1")]
      public string Property1 { get; set; }

      [JsonProperty(PropertyName = "Prop2")]
      public string Property2 { get; set; }
 }
 public class Wrapper{
      [JsonProperty(PropertyName = "MyModel")]
    public MyModel myModel{get;set;}
 }

then serialize the Wrapper object

over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!