简体   繁体   中英

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?

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

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!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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