我有一个本机序列化为的c#对象

{
  "LrsFeature": {
    "MEASURE": 1.233242,
    "STATION_ID": "brians station",
    "NLF_ID": "brians route"
  },
  "EVENT_ID": "00000000-0000-0000-0000-000000000000",
}


我希望它成为

{
  "MEASURE": 1.233242,
  "STATION_ID": "brians station",
  "NLF_ID": "brians route",
  "EVENT_ID": "00000000-0000-0000-0000-000000000000",
}


其中LrsFeature中的所有属性都添加到根级别。

我的尝试

            var events = JObject.FromObject(LrsEvent);
            var attrs = JObject.FromObject(LrsEvent.LrsFeature);

            events.Merge(attrs, new JsonMergeSettings
            {
                MergeArrayHandling = MergeArrayHandling.Union
            });


这给我

{
  "MEASURE": 1.233242,
  "STATION_ID": "brians station",
  "NLF_ID": "brians route",
  "LrsFeature": {
    "MEASURE": 1.233242,
    "STATION_ID": "brians station",
    "NLF_ID": "brians route"
  },
  "EVENT_ID": "00000000-0000-0000-0000-000000000000",
}


然后,我需要删除LrsFeature对象,但似乎有点不客气。我认为JSON.NET可能有更直接的方法

最佳答案

您可以这样操作:

    JObject jo = JObject.FromObject(LrsEvent);
    JProperty lrs = jo.Property("LrsFeature");
    jo.Add(lrs.Value.Children<JProperty>());
    lrs.Remove();
    string json = jo.ToString();


小提琴:https://dotnetfiddle.net/zsOQFE

关于c# - 将属性子对象移至根,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/43898650/

10-10 09:05
查看更多