我正在尝试将一组Hazards(我创建的类)转换为JSON,
这是我的代码:
$.ajax({
async: true,
url: web + "/GetHazards",
method: "POST",
contentType: "application/json",
success: function (data) {
var res = data.d;
var i;
alert(res[0]);
返回的数据如下:
"[{\"Hazard_ID\":3014,\"Hazard_Lat\":32.2615929,\"Hazard_Long\":35.01423},{\"Hazard_ID\":3013,\"Hazard_Lat\":32.3426857,\"Hazard_Long\":34.9103165},{\"Hazard_ID\":3012,\"Hazard_Lat\":32.3426857
我的服务器端代码返回我需要的正确值,但问题是当我提示res [i]它的行为就像res是一个字符串并提醒我“[”
我需要得到的是 {\ “Hazard_ID”:3014,\ “Hazard_Lat \”:32.2615929,\ “Hazard_Long \”:35.01423}
我不知道它是否介意这是我的服务器端代码:
{
List<Returned_Hazard> rh = new List<Returned_Hazard>();
JavaScriptSerializer json = new JavaScriptSerializer();
.
.
.
while (reader.Read())
{
Returned_Hazard RH = new Returned_Hazard(
int.Parse(reader[0].ToString()),
float.Parse(reader[1].ToString()),
float.Parse(reader[2].ToString())
);
rh.Add(RH);
}
command.Connection.Close();
return json.Serialize(rh);
}
答案 0 :(得分:3)
您需要使用JSON.parse
解析JSON:
var data = { d: "[{\"Hazard_ID\":3014,\"Hazard_Lat\":32.2615929,\"Hazard_Long\":35.01423},{\"Hazard_ID\":3013,\"Hazard_Lat\":32.3426857,\"Hazard_Long\":34.9103165}]"
};
var res = JSON.parse(data.d);
console.log(res[0].Hazard_ID); //3014