javascript - 使用 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
解决方案
为了满足您提到的要求,下面的代码应该可以工作。
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"
});
推荐阅读
- julia - 使用绘图在单独的窗口中显示两个绘图
- .net-core - Log4net 无法与 netcore 编写的 Windows 服务一起使用
- c# - 相对于线的长度向 LineRenderer 添加力?
- javascript - 使用 React Js 中的 API 实时同步按钮状态
- reverse-proxy - traefik 运行但不使用 toml 文件
- regex - 在 .htaccess 文件中使用 HTTP_HOST
- express - STRIPE“不能代表 Standard 和 Express 关联账户接受服务条款”
- sql - 在 PostgreSQL 查询的输出中获取重复值
- linux - 查找所有带有“异常”消息的 jvm 日志文件并列出 uniq 异常的计数
- python - 在 Python 控制台中捕获 Postgresql 函数返回字符串