Json fields order

萝らか妹 提交于 2019-12-11 03:07:04

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!