使用Json.NET加载带有变量名称的json的问题

时间:2014-05-03 20:18:50

标签: json.net

我的问题是使用Json.NET在此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; }
 }

1 个答案:

答案 0 :(得分:0)

由于变量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();
    }
}

要使用转换器,请在[JsonConverter]类中添加RoteBus属性,如下所示:

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

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

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