2014-01-25 3 views
2

У меня есть следующий (полный) класс сущностей.Исключая свойства обработки JSON в Struts2

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 + " ]"; 
    } 
} 

мне нужно только два свойства этого класса в качестве ответа JSON, а именно, stateId и stateName. Остальные свойства должны игнорироваться при обработке/сериализации JSON.

Я попытался установить json.excludeProperties на перехватчик json следующим образом.

@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; 
    } 
} 

Остальные свойства, как ожидается, будут проигнорированы после этого, но, похоже, это не работает. Количество операторов SQL, связанных со всеми классами сущностей генерируются в свою очередь, вызывает другие серьезные ошибки, чтобы возникнуть как,

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" 

Что я здесь отсутствует? Как игнорировать все свойства, кроме stateId и stateName?

Я использую Struts2-json-plugin-2.3.16.

ответ

3

Вам необходимо настроить includeProperties в результате json. Например,

@Result(type="json", params = {"contentType", "text/javascript", "includeProperties", 
    "stateTables\\[\\d+\\]\\.stateId,stateTables\\[\\d+\\]\\.stateName"}) 
+0

'includeProperties' работает, но' excludeProperties' не работает. Предположительно, он, кажется, был удален из последней версии. Кстати, я всегда получаю пустой ответ. Нужно ли другим библиотекам помимо «Struts2-json-plugin»? Далее я расскажу о следующем вопросе после некоторого расследования проблемы. Спасибо, сэр. – Tiny

+0

Существует 'json-lib-2.3-jdk15.jar', поставляемый с дистрибутивом. 'Список excludeProperties' доступен в' JSONResult'. Вы можете проверить вывод в браузере, введя url, который возвращает результат json, он должен показать строку JSON, вы даже можете проверить заголовки там. Я использовал 'text/javascript', но вы можете перейти на' application/json', если вам не нравится строка JSON. Также я переместил параметр «root» обратно в значение по умолчанию, если у вас есть другие свойства, которые вы также хотите вернуть с результатом. Это будет легко, добавив дополнительный параметр. –