首页 > 解决方案 > 使用 Jackson 和 PrintWriter 的 JSON 输出

问题描述

我只是将它用于我的作家

response.setContentType("application/json");
        PrintWriter out = response.getWriter();

然后我的杰克逊生成 JSON,我必须在 ajax 中检查数据,所以我想把它作为 JSON 而不是 String

对于字符串:

ObjectMapper objectMapper = new ObjectMapper();
        ToJson obj = new ToJson();
        String obj1 = objectMapper.writeValueAsString(obj);
        out.append(obj1);
        out.close();

这让{"prname1":"P1neu","anz1":"1","prid1":"1","price1":"25"}我无法使用 obj.prname1/etc 访问它

所以我在尝试这个:

response.setContentType("application/json");
        PrintWriter out = response.getWriter();

ObjectMapper objectMapper = new ObjectMapper();
        ToJson obj = new ToJson();
        String obj1 = objectMapper.writeValueAsString(obj);
        objectMapper.writeValue(out, obj1);
        System.out.println(obj);
        out.close();

但它给我留下了这个:ShoppingCart$1ToJson@4974cd9e

标签: javascriptjavajsonjacksonprintwriter

解决方案


为了满足您提到的要求,下面的代码应该可以工作。

ObjectMapper mapper = new ObjectMapper();
Cart cart = new Cart("name", 1, 2.0F);
ObjectWriter pr = mapper.writerWithDefaultPrettyPrinter();
PrintWriter pw = new PrintWriter(System.out);
PrintWriter error = new PrintWriter(System.err); //use this if you want to send errors to a different output

try {
    String output = pr.forType(Cart.class).writeValueAsString(cart);
    pw.print(output);
} catch (JsonProcessingException e) {
    pw.print("ERROR: " + e.getMessage());
} finally {
    pw.flush();
}

我用了这个简单的模型

public class Cart {
    public String name;
    public int count;
    public float price;
}

在 javascript 方面,您需要将入站字符串传递给JSON.parse()

所以例如

$.ajax({}).then((txt) => {
   //if you didn't tell the javascript library to handle the json parsing then 
  var json = JSON.parser(txt);
  console.log(json.name); //should print "name"
});

推荐阅读