MrBliz
MrBliz

Reputation: 5898

Issue parsing JSON with ServiceStack.Text

I'm using ServiceStack.Text to parse WorldWeatherOnline's Marine Api.

When Deserialising the JSON the library parses the JSON incorrectly as you can see in the second column of the image below

enter image description here

This is a part the JSON (Snipped for brevity)

{
"data":{
  "nearest_area":[
     {
        "distance_miles":"36.8",
        "latitude":"53.965",
        "longitude":"0.456"
     }
   ]
 }
}

And this is the class i'm trying to deserialize it to

 public class Weather
{
    public NearestArea NearestArea { get; set; }

}

public class NearestArea
{
    public double? RetLatitude { get; set; }
    public double? RetLongitude { get; set; }
    public double? MilesFromReq { get; set; }
}

This is the bit of code that's doing the deserialisation

Weather result = JsonObject.Parse(content).Object("data").ConvertTo(x=> new Weather{


                        NearestArea = x.Object("nearest_area").ConvertTo(n => new NearestArea{

                            MilesFromReq = Convert.ToDouble(n.Get("distance_miles")),
                            RetLatitude = Convert.ToDouble(n.Get ("latitude")),
                            RetLongitude = Convert.ToDouble(n.Get ("longitude"))

                        })

Can anyone spot the problem?

Upvotes: 2

Views: 1972

Answers (2)

L.B
L.B

Reputation: 116098

Below code should work...

var weather = ServiceStack.Text.JsonSerializer.DeserializeFromString<RootWeather>(content);


public class RootWeather
{
    public Weather data { get; set; }

}

public class Weather
{
    public List<NearestArea> nearest_area { get; set; }

}

public class NearestArea
{
    public string latitude { get; set; }
    public string longitude { get; set; }
    public string distance_miles { get; set; }
}

Upvotes: 3

rekire
rekire

Reputation: 47945

You may have also a look to the DataContractJsonSerializer. This serializer is made for such jobs.

Basically you just need to define a class with some datamember attributes the rest is done automatically. See the example on the MSDN of DataContractSerializer which do the same job just with xml.

Upvotes: 0

Related Questions