I tried the same code as on http://code.google.com/p/struts2-jquery/wiki/TreeTag
It's working fine to generate the tree structure, but I want to assign different URLs to each TreeNode of the tree. How can I do same with JSON response?
A Tree Component with a JSON Data Source.
JSP Code
<s:url var="treeDataUrl" action="json-tree-data"/>
<sjt:tree
id="jsonTree"
href="%{treeDataUrl}"
onClickTopics="treeClicked"
/>
Java Action Code
#ParentPackage(value = "showcase")
public class JsonTreeData extends ActionSupport {
private static final long serialVersionUID = -2886756982077980790L;
private List<TreeNode> nodes = new ArrayList<TreeNode>();
private String id = "";
#Actions( { #Action(value = "/json-tree-data", results = { #Result(name = "success", type = "json", params = {
"root", "nodes" }) }) })
public String execute() {
TreeNode nodeA = new TreeNode();
nodeA.setId("A" + id);
nodeA.setTitle("Node A" + id);
nodeA.setState(TreeNode.NODE_STATE_CLOSED);
TreeNode nodeB = new TreeNode();
nodeB.setId("B" + id);
nodeB.setState(TreeNode.NODE_STATE_CLOSED);
nodeB.setTitle("Node B" + id);
TreeNode nodeC = new TreeNode();
nodeC.setId("C" + id);
nodeC.setState(TreeNode.NODE_STATE_CLOSED);
nodeC.setTitle("Node C" + id);
nodes.add(nodeA);
nodes.add(nodeB);
nodes.add(nodeC);
return SUCCESS;
}
public String getJSON() {
return execute();
}
public List<TreeNode> getNodes() {
return nodes;
}
public void setId(String id) {
this.id = id;
}
}
TreeNode.java
public class TreeNode implements Serializable {
public static final String NODE_STATE_CLOSED = "closed";
public static final String NODE_STATE_OPEN = "open";
private Map<String, Object> attr;
private Collection<TreeNode> children;
private String icon;
private String id;
private String state = TreeNode.NODE_STATE_CLOSED;
private String title;
public TreeNode() {
super();
}
public TreeNode(String title) {
super();
this.title = title;
}
public TreeNode(String id, String title) {
super();
this.id = id;
this.title = title;
}
public TreeNode(String title, Collection<TreeNode> children) {
super();
this.title = title;
this.children = children;
}
public TreeNode(String id, String title, Collection<TreeNode> children) {
super();
this.id = id;
this.title = title;
this.children = children;
}
public Map<String, Object> getAttr() {
return attr;
}
public Collection<TreeNode> getChildren() {
return children;
}
/**
* Get the Tree Node Title
*/
public String getData() {
return title;
}
public String getIcon() {
return icon;
}
public String getId() {
return id;
}
public String getState() {
return state;
}
public String getTitle() {
return title;
}
public void setAttr(Map<String, Object> attr) {
this.attr = attr;
}
/**
* Set the Tree Node Childrens
*
* #param children
*/
public void setChildren(Collection<TreeNode> children) {
this.children = children;
}
/**
* Set the Tree Node Icon
*
* #param icon
*/
public void setIcon(String icon) {
this.icon = icon;
}
/**
* Set the Tree Node Id
*
* #param icon
*/
public void setId(String id) {
this.id = id;
if (this.attr == null) {
attr = new HashMap<String, Object>();
}
if (this.attr.containsKey("id")) {
this.attr.remove("id");
}
this.attr.put("id", id);
}
/**
* Set the Tree Node State open or closed
*
* #param state
*/
public void setState(String state) {
this.state = state;
}
/**
* Set the Tree Node Title
*
* #param title
*/
public void setTitle(String title) {
this.title = title;
}
#Override
public String toString() {
StringBuilder builder = new StringBuilder();
builder.append("TreeNode [id=").append(id).append(", title=").append(
title).append(", icon=").append(icon).append(", state=")
.append(state).append(", attr=").append(attr).append(
", children=").append(children).append("]");
return builder.toString();
}
}
For Each Node It generates output as
<li id="C0" class="jstree-closed jstree-last">
<ins class="jstree-icon ui-icon ui-icon-triangle-1-e"> </ins>
<a href="#" class="ui-state-default">
<ins class="jstree-icon ui-icon ui-icon-folder-collapsed"> </ins>
Node C0
</a>
</li>
I want to assign each node specific url to corresponding anchor tag generated as above.
Any help appreciated, thanks!
Related
I've make HttpsURLConnection to receive some information about my server.
The result of response is :
{"about":{"title":"NiFi","version":"1.1.0","uri":"https://localhost:443/api/","contentViewerUrl":"/nifi-content-viewer/","timezone":"CET"}}
How is possible to extract all attributes and key/value ?
About.class file
public class About {
private List<AboutObject> about;
public About()
{
// this.about = about;
}
public List<AboutObject> getAbout() {
return this.about;
}
public void setAbout(List<AboutObject> about) {
this.about = about;
}
}
AboutObject.class
public class AboutObject {
private String title;
private String uri;
private String contentViewerUrl;
private String timezone;
public String getTitle()
{
return this.title;
}
public void setTitle(String title)
{
this.title = title;
}
public String getUri()
{
return this.uri;
}
public void setUri(String uri)
{
this.uri = uri;
}
public String getContentViewerUrl()
{
return this.contentViewerUrl;
}
public void setContentViewerUrl(String contentViewerUrl)
{
this.contentViewerUrl = contentViewerUrl;
}
public String getTimeZone()
{
return this.timezone;
}
public void setTimeZone(String timezone)
{
this.timezone = timezone;
}
}
Main.class
HttpsURLConnection con = (HttpsURLConnection) obj.openConnection();
// optional default is GET
con.setRequestMethod("GET");
//add request header
con.setRequestProperty("User-Agent", USER_AGENT);
int responseCode = con.getResponseCode();
System.out.println("\nSending 'GET' request to URL : " + url);
System.out.println("Response Code : " + responseCode);
BufferedReader in = new BufferedReader(
new InputStreamReader(con.getInputStream()));
String inputLine;
StringBuffer response = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
//print result
System.out.println(response.toString());
System.out.println("Contenu de in = " + in.toString());
ObjectMapper mapper = new ObjectMapper();
//Staff objStaff = new Staff();
System.out.println("Object to JSON in file");
mapper.writeValue(new File("output/file.json"), response);
System.out.println("Convert JSON string from file to Object");
//String about = mapper.readValue(new File("output/file.json"), String.class);
About about = mapper.readValue(new File("output/file.json"), About.class);
Error
Exception in thread "main" com.fasterxml.jackson.databind.JsonMappingException: Can not construct instance of About: no String-argument constructor/factory method to deserialize from String value ('{"about":{"title":"NiFi","version":"1.1.0","uri":"https://localhost:443/api/","contentViewerUrl":"/nifi-content-viewer/","timezone":"CET"}}') at [Source: output/file.json; line: 1, column: 1]
Thanks for you help
The test json you show doesn't have the array wrapper used in your About object. You're also missing the version field in your AboutObject and the timezone field uses the wrong case.
Your example worked when I updated your objects:
public class About {
private AboutObject about;
public AboutObject getAbout() {
return about;
}
public void setAbout(AboutObject about) {
this.about = about;
}
}
public class AboutObject {
private String title;
private String uri;
private String contentViewerUrl;
private String timezone;
private String version;
public String getTitle() {
return this.title;
}
public void setTitle(String title) {
this.title = title;
}
public String getUri() {
return this.uri;
}
public void setUri(String uri) {
this.uri = uri;
}
public String getContentViewerUrl() {
return this.contentViewerUrl;
}
public void setContentViewerUrl(String contentViewerUrl) {
this.contentViewerUrl = contentViewerUrl;
}
public String getTimezone() {
return timezone;
}
public void setTimezone(String timezone) {
this.timezone = timezone;
}
public String getVersion() {
return version;
}
public void setVersion(String version) {
this.version = version;
}
}
Test:
public static void main(String[] args) throws IOException {
ObjectMapper mapper = new ObjectMapper();
String obj = "{\"about\":{\"title\":\"NiFi\",\"version\":\"1.1.0\",\"uri\":\"https://localhost:443/api/\",\"contentViewerUrl\":\"/nifi-content-viewer/\",\"timezone\":\"CET\"}}";
About about = mapper.readValue(obj, About.class);
}
I am working on deserializing the below JSON:
{"self":"http://members.cs.com/rest/api/user?username=abc#cs.com",
"key":"abc#cs.com",
"name":"abc#cs.com",
"emailAddress":"abc#cs.com",
"displayName":"ABC",
"active":true,
"members":{"size":1,"items":[{"name":"member-users","self":"http://members.cs.com/rest/api/user?username=abc#cs.com"}]},
"expand":"members"}
I have created the following classes:
#JsonIgnoreProperties(ignoreUnknown = true)
public class UserList {
private String name;
private String emailAddress;
private String displayName;
private boolean active;
List<MemberName> members = new ArrayList<>();
#JsonCreator
public UserList(#JsonProperty("name") String name, #JsonProperty("emailAddress") String emailAddress, #JsonProperty("displayName") String displayName, #JsonProperty("active") boolean active, #JsonProperty("members") List<MemberName> members) {
this.name = name;
this.emailAddress = emailAddress;
this.displayName = displayName;
this.active = active;
this.members.addAll(groups);
}
//getters
}
#JsonIgnoreProperties(ignoreUnknown = true)
public class MemberName {
private String name;
#JsonCreator
public MemberName(#JsonProperty("name") String name) {
this.name = name;
}
public String getName() {
return name;
}
}
When I don't give the members as a property the deserialization works fine and I can see the values for the name, displayName, active, emailAddress. The problem happens with the MemberName.
Could someone help with this?
This worked for me:
Class Items as below:
public class Items {
private String name;
private String self;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getSelf() {
return self;
}
public void setSelf(String self) {
this.self = self;
}
}
Members class as below:
public class Members {
private int size;
private List<Items> items;
public int getSize() {
return size;
}
public void setSize(int size) {
this.size = size;
}
public List<Items> getItems() {
return items;
}
public void setItems(List<Items> items) {
this.items = items;
}
}
Data class as below:
public class Data {
private String self;
private String key;
private String name;
private String emailAddress;
private String displayName;
private boolean active;
private Members members;
private String expand;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getSelf() {
return self;
}
public void setSelf(String self) {
this.self = self;
}
public String getKey() {
return key;
}
public void setKey(String key) {
this.key = key;
}
public String getEmailAddress() {
return emailAddress;
}
public void setEmailAddress(String emailAddress) {
this.emailAddress = emailAddress;
}
public String getDisplayName() {
return displayName;
}
public void setDisplayName(String displayName) {
this.displayName = displayName;
}
public boolean isActive() {
return active;
}
public void setActive(boolean active) {
this.active = active;
}
public Members getMembers() {
return members;
}
public void setMembers(Members members) {
this.members = members;
}
public String getExpand() {
return expand;
}
public void setExpand(String expand) {
this.expand = expand;
}
}
The deserialization as below:
public static void main(String[] args) throws JsonParseException, JsonMappingException, IOException {
String jsonString = "{\"self\": \"http://members.cs.com/rest/api/user?username=abc#cs.com\",\"key\": \"abc#cs.com\",\"name\": \"abc#cs.com\","
+ "\"emailAddress\": \"abc#cs.com\",\"displayName\": \"ABC\",\"active\": true,\"members\": {\"size\": 1,\"items\": [{"
+ "\"name\": \"member-users\",\"self\": \"http://members.cs.com/rest/api/user?username=abc#cs.com\" }]},\"expand\": \"members\"}";
ObjectMapper mapper = new ObjectMapper();
Data obj = mapper.readValue(jsonString,Data.class);
System.out.println(obj.getSelf());
System.out.println(obj.getKey());
System.out.println(obj.getName());
System.out.println(obj.getEmailAddress());
System.out.println(obj.getDisplayName());
System.out.println(obj.isActive());
System.out.println(obj.getMembers().getSize());
System.out.println(obj.getMembers().getItems().get(0).getName());
System.out.println(obj.getMembers().getItems().get(0).getSelf());
System.out.println(obj.getExpand());
}
I have table t1:
id | title
1 | title1
2 | title2
and I have the following spring repo method:
#Query(nativeQuery = true, value = "select id, title from t1")
public List<T1> getAll();
The custom class is:
public class T1 {
#JsonProperty("id")
private Integer id;
#JsonProperty("title")
private String title;
public T1(Integer id, String title) {
this.id = id;
this.title = title;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
}
I'm expecting to get the following json response:
{[{"id":1, "title":"titl1"}, {"id":2, "title":"titl2"}]}
However i'm getting this one:
[[1,"title1"],[2,"title2"]]
I'm using #RestController
#RequestMapping(method = RequestMethod.GET, value = "/test", produces = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntityTestResponse> test() {
List<T1> list = testRepository.getAll();
TestResponse response = new TestResponse(list);
return new ResponseEntity<TestResponse>(response, HttpStatus.OK);
}
TestResponse class is:
public class TestResponse implements Serializable {
private TreeSet<T1> list = new TreeSet<>();
public TestResponse(TreeSet<T1> list) {
this.list = list;
}
....
Can you help with that?
This response is classic Java List, if you need it as JSON object, you have to use for example GSON and then you should write something like this:
sonBuilder builder = new GsonBuilder();
Gson gson = builder.create();
System.out.println(gson.toJson(YOUR_LIST_OF_T1));
Here are examples (included that was i wrote) and here is GitHub repo.
You can do it manually by overrite toString() method in T1 class if u need it in specific signature, and u didn't got any API doing what you want.
So if u try some thing like that
List<T1> list = testRepository.getAll();
StringBuilder strBuilder = new StringBuilder();
for(T1 t : list){
strBuilder.append(t.toString() + ", ");
}
String result = "";
if(strBuilder.length()!=0){
result = "{[" + strBuilder.substring(0, strBuilder.length()-2) + "]}";
}
System.out.println(result);
and class should overrite toString() method
class T1{
#JsonProperty("id")
private Integer id;
#JsonProperty("title")
private String title;
public T1(Integer id, String title) {
this.id = id;
this.title = title;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
#Override
public String toString() {
return "{\"id:\"" + id + ", \"title:\"" + title + "}";
}
}
Also if you want to use pure java standard library you can do it like next code but you will need to download javax.json-xxxx.jar(for example >> javax.json-1.0.4.jar) (that include providers or the implementation) to your library project path
But this next code will generate something like that
[{"id":1,"title":"Title1"},{"id":2,"title":"Title2"},{"id":3,"title":"Title3"}]
List<T1> list = testRepository.getAll();
JsonArrayBuilder jsonArray = Json.createArrayBuilder();
for(T1 t : list) {
jsonArray.add(Json.createObjectBuilder()
.add("id", t.getId())
.add("title", t.getTitle()));
}
System.out.println(jsonArray.build());
The program compiles without errors. I can not understand why the widget is not displayed.
GreetingServise
#RemoteServiceRelativePath("springGwtServices/greetingService")
public interface GreetingService extends RemoteService {
Greeting getGreeting(String text);
void addGreeting(String author, String text);
void updateGreeting(String author, String text);
void deleteGreeting(String text);
List<Greeting> getGreetings();
}
GreetingServiceAsync
public interface GreetingServiceAsync extends RemoteService {
void getGreeting(String text, AsyncCallback<Greeting> async);
void addGreeting(String author, String text, AsyncCallback<Void> async);
void updateGreeting(String author, String text, AsyncCallback<Void> async);
void deleteGreeting(String text, AsyncCallback<Void> async);
void getGreetings( AsyncCallback<List<Greeting>> callback);
}
HelloGWT
public class HelloGWT implements IsWidget, EntryPoint {
static Logger logger = Logger.getLogger(HelloGWT.class);
private static final GreetingMapper props = GWT.create(GreetingMapper.class);
private static final GreetingServiceImpl impl = GWT.create(GreetingServiceImpl.class);
private ContentPanel panel;
public Widget asWidget() {
if (panel == null) {
ColumnConfig<Greeting, String> nameCol = new ColumnConfig<Greeting, String>(props.author(), 50, SafeHtmlUtils.fromTrustedString("<b>Company</b>"));
ColumnConfig<Greeting, String> symbolCol = new ColumnConfig<Greeting, String>(props.text(), 100, "Symbol");
List<ColumnConfig<Greeting, ?>> columns = new ArrayList<ColumnConfig<Greeting, ?>>();
columns.add(nameCol);
columns.add(symbolCol);
ColumnModel<Greeting> cm = new ColumnModel<Greeting>(columns);
ToolTipConfig config = new ToolTipConfig("Example Info", "This examples includes resizable panel, reorderable columns and grid state. Text selection is allowed.");
config.setMaxWidth(225);
ToolButton info = new ToolButton(ToolButton.QUESTION);
info.setToolTipConfig(config);
ListStore<Greeting> store = new ListStore<Greeting>(props.id());
store.addAll(impl.getGreetings());
final Grid<Greeting> grid = new Grid<Greeting>(store, cm);
grid.setAllowTextSelection(true);
grid.getView().setAutoExpandColumn(nameCol);
grid.getView().setStripeRows(true);
grid.getView().setColumnLines(true);
grid.setBorders(false);
grid.setColumnReordering(true);
// Stage manager, turn on state management
grid.setStateful(true);
grid.setStateId("gridExample");
// Stage manager, load previous state
GridStateHandler<Greeting> state = new GridStateHandler<Greeting>(grid);
state.loadState();
SimpleComboBox<String> typeCombo = new SimpleComboBox<String>(new StringLabelProvider<String>());
typeCombo.setTriggerAction(ComboBoxCell.TriggerAction.ALL);
typeCombo.setEditable(false);
typeCombo.setWidth(100);
typeCombo.add("Row");
typeCombo.add("Cell");
typeCombo.setValue("Row");
// we want to change selection model on select, not value change which fires on blur
typeCombo.addSelectionHandler(new SelectionHandler<String>() {
public void onSelection(SelectionEvent<String> event) {
boolean cell = event.getSelectedItem().equals("Cell");
if (cell) {
CellSelectionModel<Greeting> c = new CellSelectionModel<Greeting>();
c.addCellSelectionChangedHandler(new CellSelectionChangedEvent.CellSelectionChangedHandler<Greeting>() {
public void onCellSelectionChanged(CellSelectionChangedEvent<Greeting> event) {
}
});
grid.setSelectionModel(c);
} else {
grid.setSelectionModel(new GridSelectionModel<Greeting>());
}
}
});
typeCombo.addValueChangeHandler(new ValueChangeHandler<String>() {
public void onValueChange(ValueChangeEvent<String> event) {
}
});
ToolBar toolBar = new ToolBar();
toolBar.setEnableOverflow(false);
toolBar.add(new LabelToolItem("Selection Mode: "));
toolBar.add(typeCombo);
VerticalLayoutContainer con = new VerticalLayoutContainer();
con.add(toolBar, new VerticalLayoutContainer.VerticalLayoutData(1, -1));
con.add(grid, new VerticalLayoutContainer.VerticalLayoutData(1, 1));
panel = new ContentPanel();
panel.setHeadingText("Basic Grid");
panel.setPixelSize(600, 300);
panel.addTool(info);
final Resizable resizable = new Resizable(panel, Resizable.Dir.E, Resizable.Dir.SE, Resizable.Dir.S);
panel.addExpandHandler(new ExpandEvent.ExpandHandler() {
public void onExpand(ExpandEvent event) {
resizable.setEnabled(true);
}
});
panel.addCollapseHandler(new CollapseEvent.CollapseHandler() {
public void onCollapse(CollapseEvent event) {
resizable.setEnabled(false);
}
});
panel.setWidget(con);
// Enables quicktips (qtitle for the heading and qtip for the
// content) that are setup in the change GridCellRenderer
new QuickTip(grid);
}
return panel;
}
public void onModuleLoad() {
// State manager, initialize the state options
StateManager.get().setProvider(new CookieProvider("/", null, null, GXT.isSecure()));
RootPanel.get().add(asWidget());
BasicConfigurator.configure();
logger.info("Entering application.");
Bar bar = new Bar();
bar.doIt();
logger.info("Exiting application.");
}
}
GreetingMapper
public interface GreetingMapper extends PropertyAccess<Greeting> {
#Select("SELECT * FROM greetings WHERE text = #{text}")
Greeting getGreeting(#Param("text") String text);
#Select("INSERT INTO greetings (author, text) VALUES (#{author}, #{text})")
void addGreeting(#Param("author") String author, #Param("text") String text);
#Select("UPDATE greetings SET author = #{author} where text = #{text}")
void updateGreeting(#Param("author") String author, #Param("text") String text);
#Select("DELETE FROM greetings WHERE text = #{text}")
void deleteGreeting(#Param("text") String text);
#Select("SELECT * FROM greetings")
List<Greeting> getGreetings();
ModelKeyProvider<Greeting> id();
ValueProvider<Greeting, String> author();
ValueProvider<Greeting, String> text();
}
GreetingServiceImpl
#Service("greetingService")
public class GreetingServiceImpl implements GreetingService {
#Autowired
private GreetingMapper greetingMapper;
#Override
public Greeting getGreeting(String text) {
return greetingMapper.getGreeting(text);
}
#Override
public void addGreeting(String author, String text) {
greetingMapper.addGreeting(author, text);
}
#Override
public void updateGreeting(String author, String text) {
greetingMapper.updateGreeting(author, text);
}
#Override
public void deleteGreeting(String text) {
greetingMapper.deleteGreeting(text);
}
#Override
public List<Greeting> getGreetings() {
return greetingMapper.getGreetings();
}
}
Greeting
public class Greeting extends BaseModelData implements Serializable{
private Integer id;
private String author;
private String text;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getAuthor() {
return author;
}
public void setAuthor(String author) {
this.author = author;
}
public String getText() {
return text;
}
public void setText(String text) {
this.text = text;
}
}
I have the following (full) entity class.
public class StateTable implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Basic(optional = false)
#Column(name = "state_id", nullable = false)
private Long stateId;
#Column(name = "state_name", length = 45)
private String stateName;
#OneToMany(mappedBy = "stateId", fetch = FetchType.LAZY)
private Set<UserTable> userTableSet;
#OneToMany(mappedBy = "stateId", fetch = FetchType.LAZY)
private Set<City> citySet;
#OneToMany(mappedBy = "stateId", fetch = FetchType.LAZY)
private Set<Inquiry> inquirySet;
#OneToMany(mappedBy = "shippingState", fetch = FetchType.LAZY)
private Set<OrderTable> orderTableSet;
#OneToMany(mappedBy = "paymentState", fetch = FetchType.LAZY)
private Set<OrderTable> orderTableSet1;
#JoinColumn(name = "country_id", referencedColumnName = "country_id")
#ManyToOne(fetch = FetchType.LAZY)
private Country countryId;
public StateTable() {
}
public StateTable(Long stateId) {
this.stateId = stateId;
}
public Long getStateId() {
return stateId;
}
public void setStateId(Long stateId) {
this.stateId = stateId;
}
public String getStateName() {
return stateName;
}
public void setStateName(String stateName) {
this.stateName = stateName;
}
#XmlTransient
public Set<UserTable> getUserTableSet() {
return userTableSet;
}
public void setUserTableSet(Set<UserTable> userTableSet) {
this.userTableSet = userTableSet;
}
#XmlTransient
public Set<City> getCitySet() {
return citySet;
}
public void setCitySet(Set<City> citySet) {
this.citySet = citySet;
}
#XmlTransient
public Set<Inquiry> getInquirySet() {
return inquirySet;
}
public void setInquirySet(Set<Inquiry> inquirySet) {
this.inquirySet = inquirySet;
}
#XmlTransient
public Set<OrderTable> getOrderTableSet() {
return orderTableSet;
}
public void setOrderTableSet(Set<OrderTable> orderTableSet) {
this.orderTableSet = orderTableSet;
}
#XmlTransient
public Set<OrderTable> getOrderTableSet1() {
return orderTableSet1;
}
public void setOrderTableSet1(Set<OrderTable> orderTableSet1) {
this.orderTableSet1 = orderTableSet1;
}
public Country getCountryId() {
return countryId;
}
public void setCountryId(Country countryId) {
this.countryId = countryId;
}
#Override
public int hashCode() {
int hash = 0;
hash += (stateId != null ? stateId.hashCode() : 0);
return hash;
}
#Override
public boolean equals(Object object) {
// TODO: Warning - this method won't work in the case the id fields are not set
if (!(object instanceof StateTable)) {
return false;
}
StateTable other = (StateTable) object;
if ((this.stateId == null && other.stateId != null) || (this.stateId != null && !this.stateId.equals(other.stateId))) {
return false;
}
return true;
}
#Override
public String toString() {
return "model.StateTable[ stateId=" + stateId + " ]";
}
}
I need only two properties from this class as a JSON response namely, stateId and stateName. The rest of the properties must be ignored from being processed/serialized by JSON.
I have tried to set json.excludeProperties to the json interceptor as follows.
#Namespace("/admin_side")
#ResultPath("/WEB-INF/content")
#ParentPackage(value="json-default")
public final class StateListAction extends ActionSupport implements Serializable, ValidationAware
{
#Autowired
private final transient SharableService sharableService=null;
private static final long serialVersionUID = 1L;
private Long id;
List<StateTable>stateTables=new ArrayList<StateTable>();
public StateListAction() {}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
#JSON(name="stateTables")
public List<StateTable> getStateTables() {
return stateTables;
}
public void setStateTables(List<StateTable> stateTables) {
this.stateTables = stateTables;
}
#Action(value = "PopulateStateList",
results = {
#Result(type="json", name=ActionSupport.SUCCESS, params={"json.enableSMD", "true", "json.enableGZIP", "true", "json.excludeNullProperties", "true", "json.root", "stateTables", "json.excludeProperties", "userTableSet, citySet, inquirySet, orderTableSet, orderTableSet1, countryId", "validation.validateAnnotatedMethodOnly", "true"})})
public String populateStateList() throws Exception
{
System.out.println("countryId = "+id);
stateTables=sharableService.findStatesByCountryId(id);
return ActionSupport.SUCCESS;
}
}
The remaining properties are expected to be ignored after doing this but it doesn't seem to work. Number of SQL statements associated with all of the entity classes are generated which in turn causes other severe errors to occur like,
org.apache.struts2.json.JSONException: java.lang.IllegalAccessException: Class
org.apache.struts2.json.JSONWriter can not access a member of class
org.joda.time.tz.DateTimeZoneBuilder$PrecalculatedZone with modifiers "public"
What am I missing here? How to ignore all the properties except stateId and stateName?
I'm using Struts2-json-plugin-2.3.16.
You need to configure includeProperties in the json result. For example
#Result(type="json", params = {"contentType", "text/javascript", "includeProperties",
"stateTables\\[\\d+\\]\\.stateId,stateTables\\[\\d+\\]\\.stateName"})