View Full Version : Puzzling about JsonView
mophisoft
8 Jun 2007, 10:16 PM
I'm not good at English, I wish I could describe the problem clear.
When we use Ext.JsonView, we usually write codes as follows:
// Example from Ext API
var tpl = new Ext.Template(
'<div class="entry">' +
'<a class="entry-title" href="{link}">{title}</a>' +
"<h4>{date} by {author} | {comments} Comments</h4>{description}" +
"</div><hr />"
);
var moreView = new Ext.JsonView("entry-list", tpl, {
jsonRoot: "posts"
});
moreView.on("beforerender", this.sortEntries, this);
moreView.load({
url:"/blog/get-posts.php",
params: "allposts=true",
text:"Loading Blog Entries..."
});
It really can get datas from specific url, but I want to get data with java object, and the object return a list which collect any other java objects such as java beans. How to achieve it?
mophisoft
12 Jun 2007, 7:57 AM
Why doesn't anyone answer me? Doesn't anyone know the problem, or don't I make myself clear?
aconran
12 Jun 2007, 1:28 PM
If I read this correctly you are asking how to convert a java object to JSON...
I'm guessing the reason you haven't any response is because these forums really aren't focused on the server-side languages as much as the client-side javascript. Your best bet is to probably ask on a Java forum or perhaps change the topic of this thread so that someone would be able to find it.
mophisoft,
If indeed you are asking about converting java objects to JSON (and also from JSON to java objects) take a look at the java classes at http://www.json.org/java/index.html
In the example below I use a JsonReader but it illustrates how to generate the JSON from java objects to return in the ajax response.
For my java dto objects, I include the following methods,
public String toJSON() {
try {
return toJSONObject().toString();
}
catch (Exception e) {
LOGGER.debug("toJSON exception\n" + e);
return null;
}
}
public JSONObject toJSONObject() {
try {
JSONObject jsonObject = new JSONObject();
jsonObject.put("feedId", feedId);
jsonObject.put("name", name);
jsonObject.put("description", description);
jsonObject.put("category", description.trim() + " - " + name.trim());
jsonObject.put("url", url);
jsonObject.put("httpProxyConfiguration", httpProxyConfiguration);
jsonObject.put("isActive", isActive);
jsonObject.put("lastUpdateDateTime", lastUpdateDateTime);
jsonObject.put("lastUpdateUser", lastUpdateUser);
return jsonObject;
}
catch (Exception e) {
LOGGER.error("toJSON exception\n" + e);
return null;
}
}
Example of servlet/Struts action using the JSON java classes... This example returns a list of records to be load
List list = feedService.listFeed();
if (list.size() == 0) {
JSONUtil.buildJSONResponse(printWriter, StatusCode.SC_LIST_EMPTY);
return null;
}
JSONReader jsonReader = new JSONReader();
for (Iterator iterator = list.iterator(); iterator.hasNext();) {
FeedDto feedDto = (FeedDto)iterator.next();
jsonReader.put(feedDto.toJSONObject());
}
JSONUtil.buildJSONDataResponse(printWriter, jsonReader);
Custom JSONReader.java to wrap JSON for Ext JSON reader format
public class JSONReader extends JSONArray {
Integer recordCount = null;
public JSONReader() {
super();
}
public JSONReader(Integer recordCount) {
this();
this.recordCount = recordCount;
}
public String toString() {
StringBuffer sb = new StringBuffer();
if (recordCount != null) {
sb.append("{\"recordCount\":" + recordCount.toString() + ",\"rows\":");
}
else {
sb.append("{\"recordCount\":" + this.length() + ",\"rows\":");
}
sb.append(super.toString());
sb.append("}");
return sb.toString();
}
}
Helper method to build AJAX response
public static void buildJSONDataResponse(PrintWriter printWriter, JSONReader jsonReader, String message) throws Exception {
JSONDataResponse jsonDataResponse = new JSONDataResponse();
jsonDataResponse.setStatusCode(StatusCode.SC_OK);
jsonDataResponse.setMessage(message);
jsonDataResponse.setData(jsonReader.toString());
if (LOGGER.isDebugEnabled()) {
LOGGER.debug(jsonDataResponse.toJSON());
}
printWriter.write(jsonDataResponse.toJSON());
}
Ext record and datastore using JsonReader
var recordLayout = [
{name: 'feedId', mapping: 'feedId'},
{name: 'name', mapping: 'name', type: 'string'},
{name: 'description', mapping: 'description', type: 'string'},
{name: 'category', mapping: 'category', type: 'string'},
{name: 'url', mapping: 'url', type: 'string'},
{name: 'httpProxyConfiguration', mapping: 'httpProxyConfiguration', type: 'string'},
{name: 'isActive', mapping: 'isActive', type: 'bool'},
{name: 'lastUpdateDateTime', mapping: 'lastUpdateDateTime'},
{name: 'lastUpdateUser', mapping: 'lastUpdateUser', type: 'string'}
];
feedRecord = Ext.data.Record.create(recordLayout);
var dataStore = {
reader: new Ext.data.JsonReader({
totalProperty: "recordCount",
root: "rows",
id: "feedTreeId"
}, feedRecord)
};
feedDataStore = new Ext.data.Store(dataStore);
Handling the AJAX response
var result = Ext.util.JSON.decode(o.responseText);
if (result.statusCode == StatusCode.SC_SUCCESS) {
var data = Ext.util.JSON.decode(result.data);
feedDataStore.loadData(data, false);
return;
}
else if (result.statusCode == StatusCode.SC_LIST_EMPTY) {
return;
}
else {
showAlert(result);
return;
}
Hopefully this is what you are looking for...
mophisoft
12 Jun 2007, 6:42 PM
Zealous PFM, I'm extremely grateful to you, you make me known more details about json, it's also what I wanted. But your codes only had application in Ext.data.Store, my original intentions were apply them to Ext.JsonView, because I don't known how to use the 'url' in JsonView to connect a servlet/Struts action. The url seems only get datas/records through a link such as php, jsp, or asp.
mophisoft,
I have not used the JsonView. but just looking at it I would think that to go to a servlet/struts action would be no problem.
// direct load of JSON data
view.load("MyServlet...");
moreView.load({
url:"MyStrutsAction.do",
params: "allposts=true",
text:"Loading Blog Entries..."
});
And if you see the request in the servlet and build a JSON response, but the JsonView is not being updated, then I would look at the format of the JSON to make sure that it is correct.
Sorry I cannot be of anymore help with the JsonView, or if I misunderstood what your problem is... Maybe post the JS code you are trying and any JSON you are producing.
Ronaldo
22 Jul 2007, 2:32 AM
PFM, thanks for that extensive explanation!
I think it's valuable enough to put it as a 'manual' in the learning section...
fangzhouxing
20 Aug 2007, 12:58 AM
where is the code of JSONDataResponse?
august
6 Sep 2007, 11:30 PM
where is the code of JSONDataResponse?
I also want to get the code of JSONDataResponse,and i am now on the json&ext project.
herrjj
18 Feb 2008, 2:26 PM
Hi,
Thanks for the examples. This thread is a bit stale but if anyone has some insights I could use a bit of help.
How exactly is the DataReader being fed the JSON values loaded into the JSONReader array? I see that the jsonReader collection is populated with all the Beans returned by the service.
Normally, I might use request.setAttribute in order to make Java entities available to the JSP. Are you using this to then feed the values to Javascript code? If so, how?
Thanks!
Powered by vBulletin® Version 4.1.5 Copyright © 2012 vBulletin Solutions, Inc. All rights reserved.