将对象的复杂属性序列化为标量值

时间:2016-07-22 09:59:54

标签: c# json json.net

假设我们有以下类定义

public class A
{
    public string Name { get; } = "Johny Bravo";
    public B ComplexProperty { get; } = new B();
}

public class B
{
    public string Prop1 { get; } = "value1";
    public string Prop2 { get; } = "value2";
    public int Prop3 { get; } = 100;

    public override string ToString()
    {
        return this.Prop3.ToString();
    }
}
序列化时

var a = new A();
var str = JsonConvert.SerializeObject(a);

它将导致以下json字符串

{
   "Name":"Johny Bravo",
   "ComplexProperty":{
      "Prop1":"value1",
      "Prop2":"value2",
      "Prop3":100
   }
}

我们如何使ComplexProperty序列化为标量值?期望的结果必须是这个:

{
   "Name":"Johny Bravo",
   "ComplexProperty":100
}

3 个答案:

答案 0 :(得分:3)

您的代码将无法编译,因为您要将B类分配给int值 但我想我得到你想要的东西:

 class Program
    {


    static void Main(string[] args)
    {
        var a = new A();
        var str = JsonConvert.SerializeObject(a);
        Console.Write(str);
    }
}

public class A
{
    public string Name { get; } = "Johny Bravo";
    [JsonIgnore]
    public B ComplexProperty { get; } = new B();
    [JsonProperty("ComplexProperty")]
    public int complexValue => ComplexProperty.Prop3;
}

public class B
{
    public string Prop1 { get; } = "value1";
    public string Prop2 { get; } = "value2";
    public int Prop3 { get; } = 100;

    public override string ToString()
    {
        return this.Prop3.ToString();
    }
}

由于您希望对象平坦(只有1级深度),因此您需要在A类上拥有该属性。由于您不希望在json结果中包含复杂对象,因此必须忽略它,并且因为您需要在Json结果上使用相同的名称,所以必须告诉json序列化程序使用所需的序列化数据名称

答案 1 :(得分:2)

此问题的正确解决方法是使用可以处理您的类型的自定义JsonConverter。特别是在您无法控制A和B类代码的情况下。这是示例代码

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            var a = new A();
            var str = JsonConvert.SerializeObject(a, new JsonSerializerSettings()
            {
                Converters = new List<JsonConverter>()
                {
                    new BTypeJsonConverter()
                }
            });
        }
    }

    public class A
    {
        public string Name { get; } = "Johny Bravo";
        public B ComplexProperty { get; } = new B();
    }

    public class B
    {
        public string Prop1 { get; } = "value1";
        public string Prop2 { get; } = "value2";
        public int Prop3 { get; } = 100;

        public override string ToString()
        {
            return this.Prop3.ToString();
        }
    }

    public class BTypeJsonConverter : JsonConverter
    {
        public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
        {
            var b = value as B;
            if (b == null) return;
            writer.WriteValue(b.ToString());
        }

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

        public override bool CanConvert(Type objectType)
        {
            return objectType == typeof(B);
        }
    }
}

答案 2 :(得分:0)

添加另一个属性并将序列化PropertyName设置为第一个。如果您的班级A来自第三方库,请创建一个派生自A的类并添加新属性。

public class A
{
    public string Name { get; } = "Johny Bravo";
--> [JsonIgnore]
    public B ComplexProperty { get; } = new B();
 -->[JsonProperty(PropertyName = "ComplexProperty")]
--> public string ComplexPropertyText { get{ return ComplexProperty.ToString(); } }
}

public class B
{
    public string Prop1 { get; } = "value1";
    public string Prop2 { get; } = "value2";
    public int Prop3 { get; } = 100;

    public override string ToString()
    {
        return this.Prop3.ToString();
    }
}