简体   繁体   English

获取IEnumerable的JSON值 <IEnumerable<string> &gt;类型

[英]Get JSON value for IEnumerable<IEnumerable<string>> type

How to get the JSON output only value in C#. 如何在C#中获取仅JSON输出值。

I am trying to use it for type IEnumerable<IEnumerable<CustomType>> 我正在尝试将其用于IEnumerable<IEnumerable<CustomType>>

I have class with a property of type IEnumerable<IEnumerable<CustomType>> 我有一个属性为IEnumerable<IEnumerable<CustomType>>类型的类

and CustomType is defined as 并且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"}]       
]

You can do it like here, 你可以像这里一样

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);
    }
}

When you serialize a dictionary to json, it will be a json object (not array) and keys are going to be property names and values will be property values. 当您将字典序列化为json时,它将是一个json对象(不是数组),并且键将成为属性名称,而值将成为属性值。

This way is usable especially if your property names contains different characters like {"a property ..": "a value"} 特别是如果您的属性名称包含不同的字符,例如{“ a property ..”:“ a value”},则可以使用这种方法

How about converting CustomType to a dictionary? 如何将CustomType转换为字典? (You don't need to change CustomType class) (您无需更改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();

然后序列化formattedCollection

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

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