lucifer
lucifer

Reputation: 2327

How to convert java Object list to JSON and show them via AJAX

I have a list Of java object which is coming from the database as a ArrayList of object.That i have to show in a jsp page via ajax.I know how to show the arrayList of String via ajax in jsp page but i have to do the same for list of object.Here what i have done for list of String..

List<String> UnUsedStpCodeList=userService.getUnUsedSTPCodeList(100);                   
JSON json = JSONSerializer.toJSON(UnUsedStpCodeList);                   
PrintWriter out = response.getWriter(); 
out.print(json.toString()); 
System.out.println("json:" + json.toString());
response.setContentType("application/json");;

This is List of String which i am getting from the database.

var WindowHeader = "STP CODE LIST";
var htmlContent = $("#dashBoardDetails");
var myTable = "<table>";

$.ajax({
  url: "getDashBoardData.do?method=getUnUsedSTPCode",
  type: 'POST',
  cache: false,
  dataType: 'json',
  data: {
    "storeId": id
  },
  beforeSend: function() {

  },
  success: function(data, textStatus, xhr) {
    $.each(data, function(i, obj) {
      myTable += "<tr><td>" + obj + "</td></tr>";
    });
    myTable += "</table>";
    htmlContent.append(myTable);
    openWindow(WindowHeader);
  },
  error: function(xhr, textStatus, errorThrown) {
    alert('error');
  }
});

And this is how i am showing them in jsp page. Now i have

List<DashboardUserDetailsObject> registeredUserDetailsList = userService.getRegisteredDraftUserList(storeId,status);
JSON json = JSONSerializer.toJSON(registeredUserDetailsList);   
PrintWriter out = response.getWriter(); 
out.print(json.toString()); 

where registeredUserDetailsList is a list of Object which contains the information.
How can I show them in the jsp page via ajax?

Upvotes: 1

Views: 6555

Answers (1)

Jason
Jason

Reputation: 769

In javascript you access object properties using the dot syntax. Since your json will be parsed into javascript objects you can just do something like the following:

$.each(data, function(i, obj) {
    myTable += "<tr><td>"+obj.value1+"<//td><td>"+obj.value2+"<//td><//tr>";                                
});

This is assuming your object (registereduser?) has properties value1 and value2

Upvotes: 1

Related Questions