简体   繁体   English

Gson转换为Java Pojo使值变为空

[英]Gson conversion to a Java Pojo make values null

I have to persist a POJO class Community in a db using hibernate. 我必须使用休眠在数据库中保留POJO类社区。 I have this method in the class ManageCommunity: 我在类ManageCommunity中有此方法:

public void persistCommunity(String name,String domain,String idCustomer){
        Session session = sessionFactory.getCurrentSession();
        session.beginTransaction();
        Community aCommunity=new Community();
        aCommunity.setName(name);
        aCommunity.setDomain(domain);
        aCommunity.setIdCustomer(idCustomer);
       // aCommunity.setIdCommunity(aCommunity.getIdCommunity());
        session.save(aCommunity);
        session.getTransaction().commit();
    }

On the servlet with doPost i call this method and i pass the parameter of json send by postman: 在带有doPost的servlet上,我调用此方法,然后传递由postman发送的json参数:

protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

    Gson g = new Gson();
    System.out.println(CommunityHome.getBody(req));
    Community community = g.fromJson(CommunityHome.getBody(req), Community.class);
    System.out.println("Community: "+community);

    HttpSession session = req.getSession(true);
    try {
        ManageCommunity manageCommunity = new ManageCommunity();
        manageCommunity.persistCommunity(community.getName(),community.getDomain(),community.getIdCustomer());

    } catch (Exception e) {

        e.printStackTrace();
    }
}

Now value of community is null, but if i see getBody(req) there is the json 现在community的值是null,但是如果我看到getBody(req),就会发现json

This is getBody: 这是getBody:

private static String getBody(HttpServletRequest request) throws IOException {

        String body = null;
        StringBuilder stringBuilder = new StringBuilder();
        BufferedReader bufferedReader = null;

        try {
            InputStream inputStream = request.getInputStream();
            if (inputStream != null) {
                bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
                char[] charBuffer = new char[128];
                int bytesRead = -1;
                while ((bytesRead = bufferedReader.read(charBuffer)) > 0) {
                    stringBuilder.append(charBuffer, 0, bytesRead);
                }
            } else {
                stringBuilder.append("");
            }
        } catch (IOException ex) {
            throw ex;
        } /*finally {
            if (bufferedReader != null) {
                try {
                    bufferedReader.close();
                } catch (IOException ex) {
                    throw ex;
                }
            }
        }*/

        body = stringBuilder.toString();
        return body;
    }

This is POJO class: 这是POJO类:

public class Community{
    public Community(){
        UUID uuid=UUID.randomUUID();
        String random=uuid.toString();
        this.idCommunity=random;
    }



    public String getIdCommunity() {
        return idCommunity;
    }
    public void setIdCommunity(String idCommunity) {
        this.idCommunity = idCommunity;
    }
    public String getIdCustomer() {
        return idCustomer;
    }
    public void setIdCustomer(String idCustomer) {
        this.idCustomer = idCustomer;
    }
    public String getDomain() {
        return domain;
    }
    public void setDomain(String domain) {
        this.domain = domain;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }

    private String idCommunity;
    private String idCustomer;
    private String domain;
    private String name;

}

The content of CommunityHome.getBody(req) is: CommunityHome.getBody(req)的内容为:

{"idCustomer":"bb05ee35-0494-49e3-9e40-38d5dae10668", "name":"VenditaAbiti2", "domain":"Commerce2"}

Change your json to this: 将您的json更改为此:

{"IdCustomer":"bb05ee35-0494-49e3-9e40-38d5dae10668",
   "Name":"VenditaAbiti2",
   "Domain":"Commerce2"
} 

Got it working in this small example: 在这个小例子中可以正常工作:

String json = "{\"IdCustomer\":\"bb05ee35-0494-49e3-9e40-38d5dae10668\",\"Name\":\"VenditaAbiti2\",\"Domain\":\"Commerce2\"}";
        Gson g = new Gson();
        Community community = g.fromJson(json, Community.class);
        System.out.println("Community:" + community.toString());

    }

    class Community {
    @SerializedName("IdCustomer")
    private String idCustomer;

    @SerializedName("Name")
    private String name;

    @SerializedName("Domain")
    private String domain;

    @Override
    public String toString() {
        return "Community [idCustomer=" + idCustomer + ", name=" + name + ", domain=" + domain + "]";
    }

//getter setter

Output: Community:Community [IdCustomer=bb05ee35-0494-49e3-9e40-38d5dae10668, Name=VenditaAbiti2, Domain=Commerce2] 输出: Community:Community [IdCustomer=bb05ee35-0494-49e3-9e40-38d5dae10668, Name=VenditaAbiti2, Domain=Commerce2]


EDIT1: 编辑1:

Your Pojo variable names should match with the key names of your json String. 您的Pojo变量名称应与json字符串的键名匹配。 Means The json key "IdCustomer" starts with an uppercase. 表示JSON键"IdCustomer"以大写字母开头。 Your variable starts with a lower case. 您的变量以小写字母开头。 This cannot match. 这不能匹配。 But you are able to annotate your variables like in my answer. 但是您可以像我的答案一样注释变量。 There you can give the explicit name of the json key . 在那里,您可以给出json键显式名称

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM