获取IEnumerable<;的JSON值;IEnumerable<;字符串>>;类型

本文关键字:gt lt IEnumerable 类型 字符串 获取 JSON | 更新日期: 2023-09-27 18:26:54

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

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

我有一个属性类型为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"}]       
]

获取IEnumerable<;的JSON值;IEnumerable<;字符串>>;类型

,你可以在这里这样做

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类)

string json = JsonConvert.SerializeObject(collection.Select(innerList => 
              innerList.Select(type => new Dictionary<string,object>()
              {
                   {
                        type.Type, type.Value
                   }
              })));
var formatedCollections = collection.Select(c => c.Select(nest => new Dictionary<String,String>(){{nest.Type,nest.Value}})).ToArray();

然后序列化格式化的Collection