嗨,我有由哈希和列表组成的嵌套对象.我正在尝试使用gson,但是如果哈希图中的值是哈希图而不是简单字符串,则似乎无法很好地工作.
Map questionDetails = new HashMap<>();
questionDetails.put("label", descriptionNode.getText());
questionDetails.put("validations", new HashMap<>().put("compulsary", 1));
System.out.println(new Gson().toJson(questionDetails));
如果打印
{"label":"I am working on something"}
而
Map questionDetails = new HashMap<>();
questionDetails.put("label", descriptionNode.getText());
questionDetails.put("validations", "something");
System.out.println(new Gson().toJson(questionDetails));
似乎运作良好.
解决方法:
它不起作用的原因是您输入了以下内容:new HashMap<>().put(“ compulsary”,1)而不是hasmap本身.
questionDetails.put("validations", new HashMap<>().put("compulsary", 1));
做:
Map questionDetails = new HashMap<>();
questionDetails.put("label", descriptionNode.getText());
Map validations = new HashMap<>();
validations.put("compulsary", 1)
questionDetails.put("validations", validations);
System.out.println(new Gson().toJson(questionDetails));
{“validations”:{“compulsary”:1},”label”:”I am working on something”}