简体   繁体   English

转换列表 <Property> 致JObject

[英]Convert List<Property> To JObject

Consider this code: 考虑以下代码:

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

I end up with a List<JProperty> . 我最终得到了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? 有没有一种快速的方法使用Linq或JSON.NET函数将List<JProperty>对象转换为JObject而无需在循环中从头开始构建JObject?

Yup, you can just pass the list into the JObject constructor, and Json.NET will do the rest. 是的,您可以将列表传递给JObject构造函数,Json.NET将完成其余的工作。 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.) (缺少z属性,因为它的值不是字符串。)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM