I want the following structure for my Json result:
{"total":"14", "page":"1", "records":"1开发者_JAVA技巧33",
"rows":[Product {"id":"1","Code":"ANIMAL","Description":"Description1"}, Product {"id":"2","Code":"FOOD","Description":"Description FOOD"}, Product {"id":"3","Code":"CLASS","Description":"Description CLASS"}]}
But what I got is following:
{"total":"14", "page":"1", "records":"133",
"rows":[{"id":"1","Code":"ANIMAL","Description":"Description1"}, {"id":"2","Code":"FOOD","Description":"Description FOOD"}, {"id":"3","Code":"CLASS","Description":"Description CLASS"}]}
And here is the code snippet I used to generate/Serialize the Json object:
public ActionResult ReturnJSON()
{
List<Product> productRows;
productRows = new List<Product>();
foreach (Product p in apiDB.Products)
{
productRows.Add(p);
}
totalRecords = apiDB.Products.Count(); ;
totalpage = 10; // Simplified for demostration
var jsonData = new {
total = totalpage,
page = page,
records = totalRecords,
rows = productRows
};
return Json(jsonData, JsonRequestBehavior.AllowGet);
}
What's the best way to achieve that?
What you want is invalid JSON (The Product
node cannot be flying around like this):
[Product {"id":", ... }, Product {"id", ...}]
And you cannot add :
after it because rows
is an array.
There is no JSON serializer in .NET that produces invalid output. If you want to produce such result you will have to hardcode it manually yourself using strings.
look at the DataContractJsonSerializer
. Theres an example of it being used here.
http://pietschsoft.com/post/2008/02/NET-35-JSON-Serialization-using-the-DataContractJsonSerializer.aspx
in action
DataContractJsonSerializer ser = new DataContractJsonSerializer(typeof(Result));
var data = new Result() { page = 10, total = 12 };
data.Products = new ProductList { new Product { Name = "asd" }, new Product { Name = "Asddsdsd" } };
Response.Clear();
ser.WriteObject(Response.OutputStream,data);
definition of objects
[CollectionDataContract(ItemName="Product")]
public class ProductList : List<Product> {
}
public class Product{
[DataMember]
public string Description{ get; set; }
....
}
[DataContract]
public class Result {
[DataMember]
public int total { get; set; }
[DataMember]
public int page { get; set; }
[DataMember]
public ProductList Products { get; set; }
}
精彩评论