Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/272.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 序列化为JSON时如何将属性分组到子对象中_C#_Serialization_Json.net - Fatal编程技术网

C# 序列化为JSON时如何将属性分组到子对象中

C# 序列化为JSON时如何将属性分组到子对象中,c#,serialization,json.net,C#,Serialization,Json.net,鉴于这一类别: public class Thing { public string Alpha { get; set; } public string Beta { get; set; } } 我需要序列化东西的任意子类,这些子类本身可能会添加东西属性。例如 public class SomeThing : Thing { public string Delta {get; set; } public Thing ThisThing { ge

鉴于这一类别:

public class Thing
{
    public string Alpha { get; set; }
    public string Beta { get; set; }            
}
我需要序列化东西的任意子类,这些子类本身可能会添加东西属性。例如

public class SomeThing : Thing
{
  public string Delta {get; set; }

  public Thing ThisThing { get; set; }
  public Thing ThatThing { get; set; }
}
使用Newtonsoft Json.NET将某物类序列化为以下内容很容易:

{
  alpha: "x",
  beta: "x",
  delta: "x",

  thisThing: {
    alpha: "y",
    beta: "y"
  },
  thatThing: {
    alpha: "z",
    beta: "z"
  }
}
不过,我想做的是(在不更改对象或类的情况下):

也就是说,我想将任何事物属性收集到名为事物的子对象中

另一个例子:

public class SomeThingElse : Thing
{
  public int Gamma {get; set; }

  public Thing Epsilon { get; set; }
}
…将序列化为

{
  alpha: "x",
  beta: "x",
  gamma: 42,

  things: {
    epsilon: {
      alpha: "y",
      beta: "y"
    }
  }
}
通过创建一个契约解析器,我可以很容易地剥离出单独的事物属性,并将非事物本身序列化。但我不知道如何创建things属性和我剥离的属性中的内容:

public class MyContractResolver : CamelCasePropertyNamesContractResolver
{
    protected override IList<JsonProperty> CreateProperties(Type type, MemberSerialization memberSerialization)
    {
        var properties = base.CreateProperties(type, memberSerialization);

        // grab the properties that are NOT a Thing
        var toCreate = properties.Where(p => !typeof(Thing).IsAssignableFrom(p.PropertyType)).ToList();

        // grab the properties that ARE a Thing            
        var toGroup = properties.Where(p => typeof(Thing).IsAssignableFrom(p.PropertyType)).ToList();

        // create the new things property to stuff toGroup into
        var things = new JsonProperty
        {
            PropertyName = "things"
        };

        // THIS IS WHERE I'M STUCK...
        // TODO: somehow stuff toGroup into "things"

        // put the group back along with the non-thing properties
        toCreate.Add(things);

        // return the re-combined set of properties
        return toCreate;
    }            
}
产生

{
  alpha: "x",
  beta: "x",
  delta: "x"
}
请注意,即使我创建并添加了一个名为“things”的JsonProperty,它也不会出现。我的希望是,我只需要在合同分解器中的待办事项附近填补空白


或者我走错了方向。你能帮我吗?

使用C#JsonSerializer或NewtonSoft.Json。示例见:和

我认为您可能走错了方向

如果包含的对象从零到多,则可以定义属性

List<Thing> Things;
列出事物;

我相信在这一点上,json.Net可以在没有契约解析器的情况下序列化您想要的方式。

可以使用自定义的
IContractResolver
和自定义的
IValueProvider
来做您想要做的事情。试试这个:

public class MyContractResolver : CamelCasePropertyNamesContractResolver
{
    protected override IList<JsonProperty> CreateProperties(Type type, MemberSerialization memberSerialization)
    {
        var properties = base.CreateProperties(type, memberSerialization);

        // if the type is a Thing and has child properties that are things...
        if (typeof(Thing).IsAssignableFrom(type) &&
            properties.Any(p => typeof(Thing).IsAssignableFrom(p.PropertyType)))
        {
            // grab only the properties that are NOT a Thing
            properties = properties
                .Where(p => !typeof(Thing).IsAssignableFrom(p.PropertyType))
                .ToList();

            // Create a virtual "things" property to group the remaining properties
            // into; associate the new property with a ValueProvider that will do
            // the actual grouping when the containing object is serialized
            properties.Add(new JsonProperty
            {
                DeclaringType = type,
                PropertyType = typeof(Dictionary<string, object>),
                PropertyName = "things",
                ValueProvider = new ThingValueProvider(),
                Readable = true,
                Writable = false
            });
        }

        return properties;
    }

    private class ThingValueProvider : IValueProvider
    {
        public object GetValue(object target)
        {
            // target should be a Thing; we want to get its Thing properties
            // and group them into a Dictionary.
            return target.GetType().GetProperties()
                         .Where(p => typeof(Thing).IsAssignableFrom(p.PropertyType))
                         .ToDictionary(p => p.Name, p => p.GetValue(target));
        }

        public void SetValue(object target, object value)
        {
            throw new NotImplementedException();
        }
    }
}
输出:

{
  "alpha": "x.a",
  "beta": "x.b",
  "things": {
    "thisThing": {
      "alpha": "y.a",
      "beta": "y.b"
    },
    "thatThing": {
      "delta": 42,
      "alpha": "z.a",
      "beta": "z.b",
      "things": {
        "epsilon": {
          "alpha": "e.a",
          "beta": "e.b"
        }
      }
    }
  }
}

下面是另一个使用反射来获取
内容的转换器:

public class MyConverter : JsonConverter
{
    public override bool CanRead { get { return false; } }

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

    public override void WriteJson(
        JsonWriter writer,
        object value,
        JsonSerializer serializer)
    {
        var someThing = (SomeThing)value;

        var things = typeof(SomeThing).GetProperties()
            .Where(pr => pr.PropertyType.IsAssignableFrom(typeof(Thing)))
            .ToDictionary (pr => pr.Name, pr => pr.GetValue(someThing));

        var nonThings = typeof(SomeThing).GetProperties()
            .Where(pr => !pr.PropertyType.IsAssignableFrom(typeof(Thing)));

        writer.WriteStartObject();
        writer.WritePropertyName("things");
        serializer.Serialize(writer, things);

        foreach (var nonThing in nonThings)
        {   
            writer.WritePropertyName(nonThing.Name);
            serializer.Serialize(writer, nonThing.GetValue(someThing));
        }

        writer.WriteEndObject();
    }

    public override bool CanConvert(Type type)
    {
        return type == typeof(SomeThing);
    }
}

我很难理解如何尊重CamelCasePropertyNamesContractResolver
并使用转换器。

感谢您的回复:我使用的是NewtonSoft Json.NET。我一直坚持的是将这些属性“向下推”到子对象中。请不要只添加链接作为答案。仅限于两件事,或者它真的是某种类型的集合?@gravidthinks:在任意的Thing子类中可能有零个或多个Thing属性。你是对的-但是这个问题的目标是保持Thing和Thing未被触及,强制序列化程序进行分组。没错。谢谢你的回答,虽然-帮助我完善这个问题。回答很好,但没有达到我的目标(我的错不是你的错)。我将对问题进行编辑以澄清-但我需要在继承自Thing的类中发现Thing属性。@314我找到了一种方法,可以使用自定义的
IContractResolver
和自定义的
IValueProvider
来实现您想要的功能。请参阅我的最新答案。希望这更符合你的要求。万岁!非常感谢。在我的实际实现
typeof(Thing)中,我必须在ValueProvider中反转IsAssignable from。IsAssignableFrom(p.PropertyType)
而不是相反。很好用!!美好的这就是为什么我希望使用解析器,因为它从一桶准备就绪的属性开始。如果我能弄清楚如何将一个完整格式的属性添加到该bucket中就好了。@314:在这一步中,您有属性元数据,但我认为您没有序列化的实际对象。
class Program
{
    static void Main(string[] args)
    {
        SomeThing st = new SomeThing
        {
            Alpha = "x.a",
            Beta = "x.b",
            ThisThing = new Thing { Alpha = "y.a", Beta = "y.b" },
            ThatThing = new SomeThingElse 
            { 
                Alpha = "z.a", 
                Beta = "z.b",
                Delta = 42,
                Epsilon = new Thing { Alpha = "e.a", Beta = "e.b" }
            }
        };

        JsonSerializerSettings settings = new JsonSerializerSettings();
        settings.ContractResolver = new MyContractResolver();
        settings.Formatting = Formatting.Indented;

        string json = JsonConvert.SerializeObject(st, settings);

        Console.WriteLine(json);
    }
}

public class Thing
{
    public string Alpha { get; set; }
    public string Beta { get; set; }
}

public class SomeThing : Thing
{
    public Thing ThisThing { get; set; }
    public Thing ThatThing { get; set; }
}

public class SomeThingElse : Thing
{
    public int Delta { get; set; }
    public Thing Epsilon { get; set; }
}
{
  "alpha": "x.a",
  "beta": "x.b",
  "things": {
    "thisThing": {
      "alpha": "y.a",
      "beta": "y.b"
    },
    "thatThing": {
      "delta": 42,
      "alpha": "z.a",
      "beta": "z.b",
      "things": {
        "epsilon": {
          "alpha": "e.a",
          "beta": "e.b"
        }
      }
    }
  }
}
public class MyConverter : JsonConverter
{
    public override bool CanRead { get { return false; } }

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

    public override void WriteJson(
        JsonWriter writer,
        object value,
        JsonSerializer serializer)
    {
        var someThing = (SomeThing)value;

        var things = typeof(SomeThing).GetProperties()
            .Where(pr => pr.PropertyType.IsAssignableFrom(typeof(Thing)))
            .ToDictionary (pr => pr.Name, pr => pr.GetValue(someThing));

        var nonThings = typeof(SomeThing).GetProperties()
            .Where(pr => !pr.PropertyType.IsAssignableFrom(typeof(Thing)));

        writer.WriteStartObject();
        writer.WritePropertyName("things");
        serializer.Serialize(writer, things);

        foreach (var nonThing in nonThings)
        {   
            writer.WritePropertyName(nonThing.Name);
            serializer.Serialize(writer, nonThing.GetValue(someThing));
        }

        writer.WriteEndObject();
    }

    public override bool CanConvert(Type type)
    {
        return type == typeof(SomeThing);
    }
}