简体   繁体   English

反序列化一维JSON数组C#

[英]Deserialize Single Dimension JSON Array C#

assuming below multiple single-dimensional JSON Array: 假设下面有多个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" ]
}

what is the appropriate class design that could be used to deserialize it ? 可用于反序列化的合适的类设计是什么? deserialization with JSON.Net and JavascriptSerializer() works when deserializing as Dictionary<string, List<string>> but i can't seem to find the appropriate Class that is equivalent for this. JSON.Net和JavascriptSerializer()反序列化在反序列化为Dictionary<string, List<string>>但我似乎找不到与此等效的合适的Class。

below is the class design i am trying to base the deserialization with but fails: 下面是我试图基于反序列化但失败的类设计:

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

Thanks. 谢谢。

Really you need to change your json. 确实,您需要更改json。 As it stands you'll need a class something like 就目前而言,您将需要一个类似于

public class Element
{
    public List<string> F {get; set;}
    public List<string> M {get; set;}
    ....
}

To populate your existing class structure your json should be: 要填充现有的类结构,您的json应该是:

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

this makes more sense to me than what you have at the moment 对我来说,这比你现在拥有的更有意义

You have to change your JSON to make this work. 您必须更改JSON才能使其正常工作。 You have to make a list of key/value pairs: 您必须列出键/值对:

[
    {
        "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" ]
    }
]

Then you can convert it as follows: 然后,您可以将其转换如下:

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

Where RootObject is: RootObject在哪里:

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

how about this one: 这个怎么样:

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

now you have your desired object. 现在您有了所需的对象。

I guess you can create a class inherited from the dictionary: 我想您可以创建一个从字典继承的类:

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

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

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