JSON.NET customizing the serialization to exclude a property name

自闭症网瘾萝莉.ら 提交于 2019-12-23 01:19:51

问题


I am using Json.NET and I have the following code.

public class Row
{
    [JsonProperty]
    public IDictionary<string, object> Cells { get; set; }
}

The rows and cells are dynamically generated and I had C# dynamic/Expando feature to create those Cells. When Json.NET serializes the dynamic instances, it produces the correct json structure I want. However for a large data structure it has an adverse effect on the performance. For example, JsonSerializer calls DynamicObject TryGetMember quite extensively during the serialization. Therefore I needed a static data structure so the serialization would be much quicker. The synamic Expando object would still create dynamic properties, but I wanted the Json.NET serialization to use the static structure (created based on the dynamic structure) so the serialization would be much quicker.

Cells dictionary get populated based on the dynamic structure, and by invoking the JsonConvert, it produces the serialized json structure as below.

 string serializeObject =  JsonConvert.SerializeObject(data, Formatting.Indented);

//json output:

 {

    "Data": [
              {
                "Cells": {
                     "column1": "20",
                     "column2": "20"
                     }
              },
              {
                "Cells": {
                    "column1": "20",
                    "column2": "20"
                    }
              }
      ]
}

However the UI Grid which I’m binding to, require the below json structure

   "Data": [
               {
                     "column1": "20",
                     "column2": "20"                  
               },
               {                   
                    "column1": "20",
                    "column2": "20"                  
               }
           ]

Is there a way I could remove the “Cells” and produce the Json structure as above?

I looked at the JSON.NET help docos and I could not find a way to achieve this. Also tried overriding the DynamicContractResolver’s CreateProperty method to see if I can change the serialization behaviour, but I was unable to do so

 public class DynamicContractResolver : DefaultContractResolver
 {       
    protected override JsonProperty CreateProperty(System.Reflection.MemberInfo member, MemberSerialization memberSerialization)
    {
        if (member.Name == "Cells")
        {
             //remove the name "Cells" from the serialized structure    
        }
        return base.CreateProperty(member, memberSerialization);
    }
 }

Or this is not simply supported? Any suggestions or directions much appreciated.


回答1:


Found a way to get around this by creating a custom converter. The below code produces the Json result I need.

public class GridJsonConverter : JsonConverter
{
    public override bool CanConvert(Type objectType)
    {
        return true; //TODO: more logic check the type before the conversion..
    }

    public override void WriteJson(JsonWriter writer, 
       object value, JsonSerializer serializer)
    {
        var rows = (List<Row>)value;

        writer.WriteStartObject();
            writer.WritePropertyName("data");
                writer.WriteStartArray();

        foreach (var row in rows)
        {
            writer.WriteStartObject();
            var cells = row.Cells;

            foreach (var cell in cells)
            {
                writer.WritePropertyName(cell.Key);
                writer.WriteValue(cell.Value);    
            }

            writer.WriteEndObject();
        }

        writer.Flush();
    }

    public override object ReadJson(JsonReader reader, Type objectType, 
       object existingValue, JsonSerializer serializer)
    {
        throw new NotImplementedException();
    }
}

//Usage example:

  string serializeObject = JsonConvert.SerializeObject
 (someData, Formatting.Indented,   new GridJsonConverter());


来源:https://stackoverflow.com/questions/12127749/json-net-customizing-the-serialization-to-exclude-a-property-name

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!