如何在C#中从Json中删除属性容器?

时间:2017-09-14 13:35:31

标签: c# json json.net

我有一个包含多个元素的JSON问题,我想转换一些没有包含元素本身的id的JSON对象数组。基本上我想要的是转换这个结构:

{
  "SubscriptionStorages": {
    "1": {
      "Type": "subscriberstorage",
      "SubscriberStorage_Id": 1,
      "SubscriberStorage_AdminDescription": "JM Basic",
      "SubscriberStorage_MaxStorage": 268435456000
    },
    "2": {
      "Type": "subscriberstorage",
      "SubscriberStorage_Id": 2,
      "SubscriberStorage_AdminDescription": "JM Standard",
      "SubscriberStorage_MaxStorage": 536870912000
    }
  }
}

到这个结构:

{
  "SubscriptionStorages": [
    {
      "Type": "subscriberstorage",
      "SubscriberStorage_Id": 1,
      "SubscriberStorage_AdminDescription": "JM Basic",
      "SubscriberStorage_MaxStorage": 268435456000
    },
    {
      "Type": "subscriberstorage",
      "SubscriberStorage_Id": 2,
      "SubscriberStorage_AdminDescription": "JM Standard",
      "SubscriberStorage_MaxStorage": 536870912000
    }
  ]
}

有没有简单的方法呢? 这是我到目前为止所做的,但它并不好...... 我在这里缺少什么?

List<string> items = new List<string>();
if (itemsList != null)
{
    if (itemsList.Count > 0)
    {
        JToken outer = JToken.Parse(jsonBody);
        foreach (JToken t in outer)
        {
            items.Add(t.ToString());
        }
    }
}
return items;

1 个答案:

答案 0 :(得分:0)

您可以像这样转换JSON:

var jo = JObject.Parse(originalJson);

jo["SubscriptionStorages"] = new JArray(
    jo["SubscriptionStorages"]
        .Children<JProperty>()
        .Select(jp => jp.Value)
);

var modifiedJson = jo.ToString();

小提琴:https://dotnetfiddle.net/9sCx2M