Or Assayag
Or Assayag

Reputation: 6346

How to remove the attribute container from JSON in C#?

I have an issue with JSON that contains several elements, and I want to convert some JSON array of objects without the id that contain the element itself. Basically what I want is to convert this structure:

{
  "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
    }
  }
}

to this structure:

{
  "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
    }
  ]
}

Is there any simple way to do it? This is what I have so far, but it's not good... What am I missing here?

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;

Upvotes: 0

Views: 187

Answers (1)

Brian Rogers
Brian Rogers

Reputation: 129777

You can transform your JSON like this:

var jo = JObject.Parse(originalJson);

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

var modifiedJson = jo.ToString();

Fiddle: https://dotnetfiddle.net/9sCx2M

Upvotes: 1

Related Questions