反序列化单维JSON数组C#

时间:2017-04-20 09:52:46

标签: c# arrays json serialization deserialization

假设下面有多个single-dimensional JSON数组:

{
    "F" : [ "FG3D2", "FG492", "FG4Q2", "FG562", "FG5Y2", "FG6C2" ],
    "M" : [ "MG3D2", "MG492", "MG4Q2", "MG562", "MG5Y2", "MG6C2" ],
    "N" : [ "NG3D2", "NG492", "NG4Q2", "NG562", "NG5Y2", "NG6C2" ],
    "P" : [ "PG3D2", "PG492", "PG4Q2", "PG562", "PG5Y2", "PG6C2" ]
}

可用于反序列化的适当类设计是什么?使用JSON.Net和JavascriptSerializer()进行反序列化在反序列化为Dictionary<string, List<string>>时有效,但我似乎无法找到与此等效的相应类。

下面是我试图基于反序列化但仍然失败的类设计:

public class Element
{
    public string Key { get; set; }
    public List<string> Value { get; set; }
}

感谢。

4 个答案:

答案 0 :(得分:0)

你真的需要改变你的json。就目前而言,你需要一个像

这样的课程
public class Element
{
    public List<string> F {get; set;}
    public List<string> M {get; set;}
    ....
}

要填充现有的类结构,您的json应为:

[
  {"Key":"F", "Value":["FG3D2", "FG492", "FG4Q2", "FG562", "FG5Y2", "FG6C2" ]},
  {"Key":"M", "Value":["MG3D2", "MG492", "MG4Q2", "MG562", "MG5Y2", "MG6C2"]},
]

这对我来说比你现在所拥有的更有意义

答案 1 :(得分:0)

您必须更改JSON才能使其正常工作。您必须列出键/值对:

[
    {
        "Key": "F",
        "Value": [ "FG3D2", "FG492", "FG4Q2", "FG562", "FG5Y2", "FG6C2" ]
    },
    {
        "Key": "M",
        "Value": [ "MG3D2", "MG492", "MG4Q2", "MG562", "MG5Y2", "MG6C2" ]        
    },
    {
        "Key": "N",
        "Value": [ "NG3D2", "NG492", "NG4Q2", "NG562", "NG5Y2", "NG6C2" ]
    },
    {
        "Key": "P",
        "Value": [ "PG3D2", "PG492", "PG4Q2", "PG562", "PG5Y2", "PG6C2" ]
    }
]

然后你可以按如下方式转换它:

var result = JsonConvert.DeserializeObject<List<RootObject>>(json);

RootObject的位置:

class RootObject
{
    public string Key { get; set; }
    public List<string> Value { get; set; }
}

答案 2 :(得分:0)

这个怎么样:

    var dic = JsonDeserializer<Dictionary<string, List<string>>>(json);

    var els = new List<Element>();
    foreach(var k in dic.Keys)
    {
        els.Add(new Element { Key = k, Value = dic[k] });
    }

现在你有了你想要的对象。

答案 3 :(得分:-1)

我猜你可以创建一个继承自字典的类:

public class Element : Dictionary<string, List<string>>
{ }