在C#中将类的Inner属性序列化为Json对象

时间:2014-11-14 04:31:09

标签: c# json json.net

我有以下几组课程。

    public class ClassOne
    {
        [JsonProperty(PropertyName = "property1", NullValueHandling = NullValueHandling.Ignore)]
        public string Prop1 { get; set; }

        [JsonProperty(PropertyName = "property2", NullValueHandling = NullValueHandling.Ignore)]
        public string Prop2 { get; set; }

        public ClassTwo ClassTwo { get; set; }
    }

    public class ClassTwo
    {
        [JsonProperty(PropertyName = "property3", NullValueHandling = NullValueHandling.Ignore)]
        public string Prop3 { get; set; }

        [JsonProperty(PropertyName = "property4", NullValueHandling = NullValueHandling.Ignore)]
        public string Prop4 { get; set; }
    }

我需要你们的帮助,将ClassOne对象序列化为json object.Required输出:我使用Newtonsoft.Json进行序列化。

{
    "property1":"test",
    "property2":"test",
    "property3":"test",
    "property4":"test",
}

1 个答案:

答案 0 :(得分:2)

谢谢每一个人!我已按照以下方式使用自定义转换器对问题进行了排序。

    public class FlattenJsonConverter : JsonConverter
    {
        #region Public Methods

        public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
        {
            var jToken = JToken.FromObject(value);
            if (jToken.Type != JTokenType.Object)
            {
                jToken.WriteTo(writer);
                return;
            }

            var jObject = (JObject)jToken;
            writer.WriteStartObject();
            WriteJson(writer, jObject);
            writer.WriteEndObject();
        }

        private void WriteJson(JsonWriter writer, JObject value)
        {
            foreach (var property in value.Properties())
            {
                var jObject = property.Value as JObject;
                if (jObject != null)
                    WriteJson(writer, jObject);
                else
                    property.WriteTo(writer);
            }
        }

        public override object ReadJson(JsonReader reader, Type objectType,
           object existingValue, JsonSerializer serializer)
        {
            return null;
        }

        public override bool CanConvert(Type objectType)
        {
            return true;
        }

        #endregion
    }

用法:

    // To Flatten the Json result
    var settings = new JsonSerializerSettings
    {
        Formatting = Formatting.Indented,
        Converters = new List<JsonConverter> { new FlattenJsonConverter() },
    };

    var serializedJsonObject = JObject.Parse(testclassObject, settings));