Convert List<Property> To JObject

Jazimov picture Jazimov · Nov 9, 2016 · Viewed 9.3k times · Source

Consider this code:

var joWork = ((JObject) x).Properties()
    .Where(p => p.Value.Type == JTokenType.String).ToList();

I end up with a List<JProperty>.

Is there a quick way using Linq or a JSON.NET function to convert that List<JProperty> object to a JObject without building a JObject from scratch in a loop?

Answer

Jon Skeet picture Jon Skeet · Nov 9, 2016

Yup, you can just pass the list into the JObject constructor, and Json.NET will do the rest. Here's an example:

using System;
using System.Linq;
using Newtonsoft.Json.Linq;

public class Test
{
    static void Main()
    {
        JObject original = JObject.Parse("{ \"x\": \"a\", \"y\": \"b\", \"z\": 1 }");
        var properties = original
            .Properties()
            .Where(p => p.Value.Type == JTokenType.String)
            .ToList();

        var recreated = new JObject(properties);
        Console.WriteLine(recreated);
    }
}

Output:

{
  "x": "a",
  "y": "b"
}

(The z property is missing because its value isn't a string.)