繁体   English   中英

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

[英]Deserialization of Json without name fields

我需要反序列化以下 Json,根据 Jsonlint.com 是有效的,但我以前没有遇到过或者找不到类似 Json 的例子以及如何处理它?

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

我目前的系统是这样的:

数据类:

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

解串器:

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

我现有的反序列化器使用完整的 Json 流并对其进行迭代,但在我的新 Json 中,我需要反序列化,它只有 1 个项目,因此我不需要对其进行迭代。

那么是否可以使用与我目前类似的方法反序列化我的 Json 示例?

我会说你试图把事情复杂化。 您拥有的是一个完美形成的 json 字符串数组。 如果我是你,我会先将它反序列化为 .net 数组,然后编写一个“映射器”函数来复制值:

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

等等。 当然,这假设您知道 json 的顺序,但是如果您首先尝试这样做,那么您必须这样做!

暂无
暂无

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

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