Deserialization of Json without name fields

非 Y 不嫁゛ 提交于 2019-12-11 07:38:01

问题


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?

[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.

So is it possible to deserialize my Json example using a similar method than I currently do?


回答1:


I would say that you are attempting to overcomplicate things. What you have is a perfectly formed json array of strings. If I were you I would deserialize that to an .net array first, and then write a 'mapper' function to copy the values across:

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!



来源:https://stackoverflow.com/questions/13691493/deserialization-of-json-without-name-fields

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!