使用Json的问题.用变量名加载json



我的问题是用json加载这个URL中的json。净:http://www.poatransporte.com.br/php/facades/process.php?a=il& p = 5399

以下是JSON的一个简短示例供参考:

{
    "0": {
        "lat": "-30.03087344108400000",
        "lng": "-51.22585742359100000"
    },
    "1": {
        "lat": "-30.03094644108400000",
        "lng": "-51.22480142359100000"
    },
    "2": {
        "lat": "-30.03099144108400000",
        "lng": "-51.22434242359100000"
    },
    "190": {
        "lat": "-30.11229544108400000",
        "lng": "-51.24937242359100000"
    },
    "191": {
        "lat": "-30.11159444108400000",
        "lng": "-51.24973042359100000"
    },
    "idlinha": "5399",
    "nome": "CAMAQUA ",
    "codigo": "173-2"
}

RoteBus.rote的值始终为空。有人能帮帮我吗?

我使用的代码是:

 WebClient webClient2 = new WebClient();
 webClient2.DownloadStringCompleted += new DownloadStringCompletedEventHandler(itinerario);
 webClient2.DownloadStringAsync(new Uri("http://www.poatransporte.com.br/php/facades/process.php?a=il&p=5399"));
 void itinerario(object sender, DownloadStringCompletedEventArgs e)
 {
    RoteBus rootObject = JsonConvert.DeserializeObject<RoteBus>(e.Result);
    Debug.WriteLine("rootObject.rote = " + rootObject.rote);
 }
 public class Rote
 {
     public string lat { get; set; }
     public string lng { get; set; }
 }
 public class RoteBus
 {
     public string idlinha { get; set; }
     public string nome { get; set; }
     public string codigo { get; set; }
     public Dictionary<string, Rote> rote { get; set; }
 }

由于变量Rote数据与RoteBus的固定属性混合的方式,您将需要自定义JsonConverter类来完成此工作。下面是一种写法:

public class RoteBusConverter : JsonConverter
{
    public override bool CanConvert(Type objectType)
    {
        return (objectType == typeof(RoteBus));
    }
    public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
    {
        JObject jo = JObject.Load(reader);
        RoteBus rb = new RoteBus { rote = new Dictionary<string, Rote>() };
        foreach (JProperty prop in jo.Properties())
        {
            if (prop.Name == "idlinha") 
                rb.idlinha = prop.Value.ToString();
            else if (prop.Name == "nome") 
                rb.nome = prop.Value.ToString();
            else if (prop.Name == "codigo") 
                rb.codigo = prop.Value.ToString();
            else 
                rb.rote.Add(prop.Name, prop.Value.ToObject<Rote>());
        }
        return rb;
    }
    public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
    {
        throw new NotImplementedException();
    }
}

要使用转换器,向RoteBus类添加一个[JsonConverter]属性,如下所示:

[JsonConverter(typeof(RoteBusConverter))]
public class RoteBus
{
    ...
}

然后像往常一样反序列化:

RoteBus rootObject = JsonConvert.DeserializeObject<RoteBus>(e.Result);

相关内容

  • 没有找到相关文章

最新更新