JSON master-detail structure
I am trying to model a simple invoice that has an invoice object with minimally an ArrayList and an lineitem object with an ArrayList of the values for a given row开发者_开发问答. I get my result-set, loop over it and every time create a new lineitem object, populate the lineitem ArrayList with the desired field values and then add that lineitem to the invoice ArrayList. I then add this to a JSONArray and then "flatten" it with toString() to get my json string to send to the client. The problem is all the lines are there but as a "bare" array of lineitem objects. I need another structure that I can loop on client-side, access each lineitem object, and print the row to the screen and continue. How do I structure it so I have and "outer" object that I can loop over to process the lineitems?
You need to "parse" the values / array on the server side to build up a string that can be interpreted as JSON on the client. There are lots of libraries (both server & client side that can help you with this). Ultimately you need a string that looks somthing like the following when it arrives on the client side.
var strJsonInvoive = "[InvoiceID : 1, Date : "01/01/1900", otherProperties: "value" ,
//the Invoice Detail Objects below will result in an array of objects
InvoiceDetails : [InvoiceDetailID : 1, Description: "desc", Price: 100, Quantity: 1, Tax: true],
[InvoiceDetailID : 2, Description: "desc", Price: 200, Quantity: 2, Tax: false],
[InvoiceDetailID : 3, Description: "desc", Price: 300, Quantity: 3, Tax: true]]";
At this point, the above is purely a string, so again, you need to Parse this client side to turn this into an object, for example you could use jQuery to Parse the json string as follows :
var jsonInvoice = jQuery.parseJSON(strJsonInvoice);
Now, you will have an object that you can work with as follows :
for(var 1=0; i<jsonInvoice.InvoiceDetails.length;i++)
{
if (jsonInvoice.InvoiceDetails[i].Price > 50)
//do something if price is greater than 50
}
Hope this helps.
Dave
精彩评论