回应
< script >
$(document).ready(function() {
$.ajax({
url: "http://localhost:37994/odata/EPStructures3/",
type: "Get",
contentType: 'application/json; odata=nometadata; charset=utf-8',
success: function(data)
{
var arr_from_json = JSON.parse(data);
//do something.....
},
error: function(msg)
{
alert(msg);
}
});
});
< /script>
我收到以下 JSON
{"value":[{"eps_level":0,"id":2},{"eps_level":1,"id":3}]}
我想将其转换为 this (尝试使用 JSON.parse(data)),但它不起作用
[{"eps_level":0,"id":2},{"eps_level":1,"id":3}]
我的类(class)是
[Table("EPStructure")]
public partial class EPStructure
{
public byte eps_level { get; set; }
[Key]
[Column("eps_id")]
public int id { get; set; }
}
我怎样才能实现这个目标?
最佳答案
返回的数据为JSON格式。所以它实际上是一个 JavaScript 对象(JavaScript Object Notation)。您想要删除包含带有对象的数组的对象。
只需执行以下操作:
var arr_from_json = JSON.parse(data).value; //parse it into a JavaScript Object, call its property value. This will return an array
将其解析为 JavaScript 是正确的。从那时起,您可以正常对待该对象并从中检索属性。在本例中,数组存储在 value
属性中。
工作示例:
var data = '{"value":[{"eps_level":0,"id":2},{"eps_level":1,"id":3}]}'; //this line represents the object returned from the ajax call;
var arr_from_json = JSON.parse(data).value;
//you can access eps_level by doing this: arr_from_json[0].eps_level
document.body.innerHTML += JSON.stringify(arr_from_json);// for demo purposes. This line is not part of the solution.
正如 Joe Enos 评论的那样:如果您在此处使用 jQuery 功能 dataType
,您可以跳过 JSON.parse
步骤,因为 data
将包含解析后的 JSON。
关于javascript - 将 OData 转换为 JSON,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28949629/