序列化为JSON对象<string,string =“”> </string,>的数组

时间:2015-04-10 17:19:47

标签: c# json

我需要我的JSON输出如下(对象数组):

{
    "values":[{"1","one"},{"2","two"},{"3","three"},{"4","four"}]
}

但是,当我序列化以下C#类时:

public class MyObject
{
    public List<string>[] values {get;set}
}

它产生以下(数组数组):

{
    "values":[["1","one"],["2","two"],["3","three"],["4","four"]]
}

我在这个对象上尝试了很多变化。如下所示:

public class MyObject
{
    public KeyValuePair[] values {get;set}
}

这给了我(KeyValuePair数组):

{
    "values":[{"Key":"1","Value":"one"},{"Key":"2","Value":"two"},{"Key":"3","Value":"three"},{"Key":"4","Value":"four"}]
}

是否有一个C#对象属性会序列化为没有包含对象属性名称的json对象数组?:

{
    "values":[{"1","one"},{"2","two"},{"3","three"},{"4","four"}]
}

1 个答案:

答案 0 :(得分:1)

我可能在这里回答我自己的问题,但这是我找到的。以下将返回没有属性名称的对象数组。但是,它是一个hack并使用Dictionary Key作为json属性名称:

public class MyObject
{
    public Dictionary<string, string>[] values { get; set; }
}

产生以下结果:

{
"values":[{"1":"one"},{"2":"two"},{"3":"three"},{"4":"four"}]
}