JsonConvert.SerializeObject Turning Double Into String

时间:2016-03-11 17:45:08

标签: c# json serialization json.net

I'm passing in an object to JsonConvert.SerializeObject, in hopes of turning said object into a json string for use with an API....before serialization this is what the object looks like:

var hotelBedsSearchRequest = new HotelBedsSearchRequest()
            {
                stay = new Stay
                {
                    checkIn = "2016-06-08",
                    checkOut = "2016-06-10",
                    shiftDays = "2"
                },
                occupancies = new Occupancy[]
                {
                    new Occupancy
                    {
                        rooms = 1,
                        adults = 2,
                        children = 1,
                        paxes = new Pax[]
                        {
                            new Pax
                            {
                                type = "AD",
                                age = 30
                            },
                            new Pax
                            {
                                type = "AD",
                                age = 30
                            },
                            new Pax
                            {
                                type = "CH",
                                age = 8
                            }
                        }
                    }
                },
                geolocation = new Geolocation
                {
                    longitude = 2.646633999999949,
                    latitude = 39.57119,
                    radius = 20,
                    unit = "km"
                }
            };

All fields serialize fine except for latitude and longitude which when I serialize to a JSON string and view as json in visual studio looks like this:

enter image description here

为什么lat和long作为字符串出现?它被指定为类模式中的double类型...我尝试过两种最常见的序列化技术(Newtonsoft和内置)都做同样的事情......当我运行API时,我得到一个400错误的错误请求和我认为这是对lat和long数据类型的误解......不确定但是任何帮助都会很棒!

这是Geolocation类:

    public class Geolocation
{
    public double longitude { get; set; }
    public double latitude { get; set; }
    public int radius { get; set; }
    public string unit { get; set; }
}

这是序列化的JSON输出文本:

{"stay":{"checkIn":"2016-06-08","checkOut":"2016-06-10","shiftDays":"2"},"occupancies":[{"rooms":1,"adults":2,"children":1,"paxes":[{"type":"AD","age":30},{"type":"AD","age":30},{"type":"CH","age":8}]}],"geolocation":{"longitude":2.6466341018676758,"latitude":39.571189880371094,"radius":20,"unit":"km"},"adults":0} 

这是序列化和API调用:

var json = new JavaScriptSerializer().Serialize(request);
var response = client.UploadString(endpoint, "POST", json);
var ans = DeserializeResult(response);

1 个答案:

答案 0 :(得分:0)

修正了,它与传递错误的结构无关,请求类简单地构建错误...抱歉。我没有意识到,即使你没有为模式中的某个字段传递任何东西,它仍然会在你上课时显示