Jagat Singh
Jagat Singh

Reputation: 43

C# WebApi - Json serialize bring a property to higher level

I have a class with following structure

class Model
{
   public int Id {get;set;}
   public Dictionary<string, List<ComplexType>> Values {get;set;}
}

utilized in an Dotnetcore webApi project and returned from my controller as the following object

Ok(new List<Model>() { 
new Model{
  Id = 1,
  Values = new Dictionary<string, List<ComplexType>>() { {"Item1", new List<ComplexType>()} }
} } )

which would produce Json output as :

[
     {
         "Id": "1"
         "Values": {
           "Item1": [{}]
          }
     }
]

So my question is any way possible, to bring the Dictionary property name to a higher level in output Json structure. Basically Omitting the property name "Values" in "Model" class and merging lower object so it would look something like this:

[
     {
         "Id": "1"
         "Item1": [{}]
     }
]

Upvotes: 0

Views: 435

Answers (2)

Gaurav Mathur
Gaurav Mathur

Reputation: 849

You can write your own serializer, its simpler then you think and you'll have way more control on generated json.

class Model
{
    public int Id { get; set; }
    public Dictionary<string, List<ComplexType>> Values { get; set; }

    public string ToJson()
    {
        return
            $"{{" +
            $"\"{nameof(Id)}\":\"{Id}\"," +
            string.Join(",", Values.Select(x => $"\"{x.Key}\":" + Newtonsoft.Json.JsonConvert.SerializeObject(x.Value))) +
            $"}}";
    }
}

Then call it like this -

var json = "[" + string.Join(",", obj.Select(x => x.ToJson())) + "]";

Finally return the above json as response.

var response = this.Request.CreateResponse(HttpStatusCode.OK);
response.Content = new StringContent(json, Encoding.UTF8, "application/json");
return response;

Upvotes: 0

Steve
Steve

Reputation: 11963

You can remove that Value property all together and make Model a dictionary type

class Model : Dictionary<string, List<ComplexType>> 
{
     public int Id { get; set; } 
} 

then you can just do

var model = new Model();
model.Id = 123;
model["Item1"] = new List<ComplexType>();

Upvotes: 1

Related Questions