简体   繁体   English

没有名称字段的 Json 反序列化

[英]Deserialization of Json without name fields

I need to deserialize the following Json, which according to Jsonlint.com is valid, but ive not come across this before or cannot find examples of similar Json and how to deal with it?我需要反序列化以下 Json,根据 Jsonlint.com 是有效的,但我以前没有遇到过或者找不到类似 Json 的例子以及如何处理它?

[1,"Bellegrove  / Sherwood ","76705","486","Bexleyheath Ctr",1354565507000]

My current system with like this:我目前的系统是这样的:

Data class:数据类:

[DataContract]
public class TFLCollection 
{ [DataMember(Name = "arrivals")]
    public IEnumerable<TFLB> TFLB { get; set; } 
}
[DataContract]

public class TFLB
{ 
    [DataMember]
    public string routeName { get; set; }
    [DataMember]    
    public string destination { get; set; }
    [DataMember]    
    public string estimatedWait { get; set; } 
}

Deserializer:解串器:

DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(TFLCollection));

                using (var stream = new MemoryStream(Encoding.Unicode.GetBytes(result))) 
                {     var buses = (TFLCollection)serializer.ReadObject(stream);
                foreach (var bus in buses.TFLBuses)     
                    {
                        StopFeed _item = new StopFeed();

                         _item.Route = bus.routeName;
                          _item.Direction = bus.destination;
                          _item.Time = bus.estimatedWait;

                          listBox1.Items.Add(_item);

My exsiting deserializer works with a full Json stream and iterates through it, but in my new Json I need to deserialize, it only have 1 item, so I wont need to iterate through it.我现有的反序列化器使用完整的 Json 流并对其进行迭代,但在我的新 Json 中,我需要反序列化,它只有 1 个项目,因此我不需要对其进行迭代。

So is it possible to deserialize my Json example using a similar method than I currently do?那么是否可以使用与我目前类似的方法反序列化我的 Json 示例?

I would say that you are attempting to overcomplicate things.我会说你试图把事情复杂化。 What you have is a perfectly formed json array of strings.您拥有的是一个完美形成的 json 字符串数组。 If I were you I would deserialize that to an .net array first, and then write a 'mapper' function to copy the values across:如果我是你,我会先将它反序列化为 .net 数组,然后编写一个“映射器”函数来复制值:

public TFLB BusRouteMapper(string[] input)
{
    return new TFLB {
        Route = input[x],
        Direction = input[y],
    };
}

And so on.等等。 Of course this assumes that you know what order your json is going to be in, but if you are attempting this in the first place then you must do!当然,这假设您知道 json 的顺序,但是如果您首先尝试这样做,那么您必须这样做!

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

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