不带名称字段的Json的反序列化

不带名称字段的Json的反序列化

本文介绍了不带名称字段的Json的反序列化的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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:

数据类:

[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个项目,因此我不需要对其进行迭代.

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示例吗?

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

推荐答案

我要说的是,您正在尝试使事情变得过于复杂.您所拥有的是一个完美形成的json字符串数组.如果您是我,我会先将其反序列化为.net数组,然后编写一个映射器"函数以在以下位置复制值:

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

以此类推.当然,这是假设您知道json的顺序,但是如果首先尝试这样做,则必须这样做!

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的反序列化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-02 11:22