Gson doesn't parse an exposed field

白昼怎懂夜的黑 提交于 2019-12-25 03:22:55

问题


I have the following POJO's:

public class Prices implements Serializable{
    private static final long serialVersionUID = 1L;
    @Expose private Integer idPrice;
    @Expose private String date;
    @Expose private Double price;
    @Expose private OrderLine orderLine;

    public Prices(){}
    // getters and setters
}

public class OrderLine implements Serializable {
    private static final long serialVersionUID = 1L;
    @Expose private Integer idOrderLine;
    @Expose private Articles art;
    @Expose private Integer q;

    private List<Prices> prices;

    public OrderLine(){}
    // getters and setters  
}

I'm trying to parse a price object to JSON by using the following method:

Gson gson = new GsonBuilder().excludeFieldsWithoutExposeAnnotation().create();
String response = gson.toJson(price);

... but somehow GSON doesn't parse the OrderLine contained in the Price object.
If i do:

 System.out.println("Price: " + response);

I get the following answer:

Price: {"idPrice":1,"date":"2014-08-24","price":37.0,"orderLine":{}}

I'm using Hibernate too but I don't think it is the problem because if I do:

System.out.println(price);

... then I get the whole object data.

What am I doing wrong ?

Update:

This is how i initialize my price variable. (must say i'm new to Hibernate and Gson)

public static String getPrice(Integer idPrice) {

  Session session = HibernateUtil.getSessionFactory().openSession();
  Transaction tx = session.beginTransaction();

  String hql = "from Prices p where p.idPrice = :idPrice";

  Prices price = (Prices) session.createQuery(hql)
                  .setParameter("idPrice", idPrice)
                  .uniqueResult();

  Gson gson = new GsonBuilder().excludeFieldsWithoutExposeAnnotation().create();
  String response = gson.toJson(price);


  // i have added the following code just to see what results i was getting
  System.out.println(price); <--- this shows all the object's data
  System.out.println(response); <-- this shows Price: {"idPrice":1,"date":"2014-08-   24","price":37.0,"orderLine":{}}


  tx.commit();
  session.flush();
  session.close();

  return response;
}

来源:https://stackoverflow.com/questions/25476712/gson-doesnt-parse-an-exposed-field

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!