使用JsonConvert.DeserializeObject反序列化Json

时间:2017-01-03 10:14:07

标签: c# .net json xamarin

我有以下要转换为对象City的字符串。这不起作用,但抛出:

  

无法解析类型:global :: Newtonsoft.Json.JsonConvert.DeserializeObject

Jsonstring:

{"result":{"id_city":"XX","city_name":"XXXX","city_province":"BW","city_country":"DE","city_zipcode":null,"city_gps_lat":"XXXXXX","city_gps_lng":"XXXXXX","city_gps_geohash":"XXXXXX","city_image":"XXXXXX","distance":11111}}

城市课程:

 public class City
 {
      [JsonProperty("id_city")]
      public string id_city { get; set; }
      [JsonProperty("city_name")]
      public string city_name { get; set; }
      [JsonProperty("city_province")]
      public string city_province { get; set; }
      [JsonProperty("city_country")]
      public string city_country { get; set; }
      [JsonProperty("city_zipcode")]
      public string city_zipcode { get; set; }
      [JsonProperty("city_gps_lat")]
      public string city_gps_lat { get; set; }
      [JsonProperty("city_gps_lng")]
      public string city_gps_lng { get; set; }
      [JsonProperty("city_gps_geohash")]
      public string city_gps_geohash { get; set; }
      [JsonProperty("city_image")]
      public string city_image { get; set; }
      [JsonProperty("distance")]
      public string distance { get; set; }
}

方法调用:

City stadt = JsonConvert.DeserializeObject<City>(Jsonstring);

通过NuGet

安装Newtonsoft.Json 8.0.3

1 个答案:

答案 0 :(得分:2)

您的字符串表示result属性为City类型的类。

public class YourResultClass
{
    public City result { get; set; }
}

您可以将字符串反序列化为YourResultClass

YourResultClass stadt = JsonConvert.DeserializeObject<YourResultClass>(Jsonstring);

您可以使用JSonEditorOnline来检查您的json字符串代表什么。