获取 IEnumerable<IEnumerable<string>> 类型的 JSON 值

Get JSON value for IEnumerable<IEnumerable<string>> type

如何在 C# 中获取 JSON 仅输出值。

我正在尝试将其用于类型 IEnumerable<IEnumerable<CustomType>>

我有 class,属性 类型为 IEnumerable<IEnumerable<CustomType>>

CustomType 定义为

public class CustomType{
    public string Type {get;set;}
    public string Value {get;set;}
}

var data = JsonConvert.SerializeObject(collection);

The result i am getting is 

[
    [   
        {"Type":"Role","Value":"RoleA"},
        {"Type":"Role","Value":"RoleB"}
    ],
    [
        {"Type":"Role","Value":"RoleC"}
    ],
    [
        {"Type":"Buyer","Value":"UserA"}
    ],
    [
        {"Type":"Seller","Value":"UserB"}
    ]
]

I need following output
[
    [{"Role" : "RoleA"},{"Role" : "RoleB"}],
    [{"Role" : "RoleC"}],
    [{"Buyer" : "UserA"}]       
]
var formatedCollections = collection.Select(c => c.Select(nest => new Dictionary<String,String>(){{nest.Type,nest.Value}})).ToArray();

然后序列化formatedCollection

你可以像这里一样做,

public class CustomType
{
    public string Type { get; set; }
    public string Value { get; set; }

    public Dictionary<string, string> AsJsonProperty()
    {
        return new Dictionary<string, string>
        {
            {Type, Value}
        };
    }
}

class Class1
{
    public string ToJson(IEnumerable<IEnumerable<CustomType>> customTypes)
    {
        var asJsonFriendly = customTypes.Select(x => x.Select(y => y.AsJsonProperty()));
        return JsonConvert.SerializeObject(asJsonFriendly);
    }
}

当您将字典序列化为 json 时,它将是一个 json 对象(不是数组)并且键将是 属性 名称,值将是 属性 值。

这种方式非常有用,尤其是当您的 属性 名称包含不同的字符时,例如 {"a property ..": "a value"}

如何将 CustomType 转换为字典? (您不需要更改 CustomType class)

string json = JsonConvert.SerializeObject(collection.Select(innerList => 
              innerList.Select(type => new Dictionary<string,object>()
              {
                   {
                        type.Type, type.Value
                   }
              })));