问题
I have a model stored with RavenDB done in this way:
public abstract class Animal
{
public string Id { get; set; }
public int LegsNumber { get; set; }
}
public class Giraffe: Animal
{
public double NeckLength { get; set; }
}
In my MVC controller I query all the Giraffe and put the result in Json format in this way:
return new JsonResult
{
JsonRequestBehavior = System.Web.Mvc.JsonRequestBehavior.AllowGet,
Data = DocumentSession.Query<Giraffe>()
};
The output is something like
[{"NeckLength":2.5, "Id":"bob", "LegsNumber":4}, {...}, ...]
How can I customize the field order in order to have a result like this:
[{"Id":"bob", "LegsNumber":4, "NeckLength":2.5}, {...}, ...]
?
If you are curious and you want to know why I want to change the order is because I have a generic javascript snippet that take the json and print it out as it is:
for (var field in data[0]) {
var row = '<tr>';
row += '<td><b>' + field + '</b></td>'
$.each(data, function (i, value) {
row += '<td>' + value[field] + '</td>'
});
row += '</tr>';
result += row;
}
回答1:
Try attributing your fields with JsonPropertyAttribute like this:
public abstract class Animal
{
[JsonProperty(Order = 0)]
public string Id { get; set; }
[JsonProperty(Order = 1)]
public int LegsNumber { get; set; }
}
public class Giraffe: Animal
{
[JsonProperty(Order = 2)]
public double NeckLength { get; set; }
}
回答2:
Json is not providing an index based access. Instead you can try something like this
for (int i = 0; i < Data.length(); i++) {
var item=Data.[i];
var row = '<tr>';
row += '<td><b>' +item['Id'] + '</b></td>'+'<td><b>' +item['LegsNumber'] + '</b></td>'
+item['NeckLength'] + '</b></td>'+'<tr>';
}
来源:https://stackoverflow.com/questions/12616976/json-fields-order