【发布时间】:2014-05-11 14:34:24
【问题描述】:
我在 servlet 中有一个 Java 类,它使用 GSON 将发布的 JSON 字符串呈现为 Java 对象。该方法的美妙之处在于,GSON 过滤掉了所有与类属性不匹配的 JSON 元素,因此我永远不会得到我不想处理的 JSON 内容。 servlet 的 doPost(简化)如下所示:
protected void doPost(HttpServletRequest request, HttpServletResponse response) {
PrintWriter out = null;
try {
InputStream in = request.getInputStream();
Demo d = Demo.load(in);
in.close();
response.setContentType("text/plain");
response.setStatus(HttpServletResponse.SC_OK);
out = response.getWriter();
out.println(d.toJson);
} catch (Exception e) {
e.printStackTrace();
out.println(e.getMessage());
}
out.close();
}
Demo 类(这是我需要在 common.js 或 node.js 中重新创建的类,如下所示:
@JsonIgnoreProperties(ignoreUnknown = true)
public class Demo implements Serializable {
public static Demo load(InputStream in) {
Demo result = null;
try {
Gson gson = new GsonBuilder().create();
result = gson.fromJson(new InputStreamReader(in), Demo.class);
} catch (Exception e) {
result = null;
}
return result;
}
@TypeDiscriminator
@JsonProperty("_id")
private String id = UUID.randomUUID().toString();
private Date created = new Date();
private String color;
private String name;
private String taste;
public String getColor() {
return this.color;
}
public String getName() {
return this.name;
}
public String getTaste() {
return this.taste;
}
public Date getCreated() {
return this.created;
}
public String getId() {
return this.id;
}
public void setName(String name) {
this.name = name;
}
public void setTaste(String taste) {
this.taste = taste;
}
public void setColor(String color) {
this.color = color;
}
public String toJson() {
GsonBuilder gb = new GsonBuilder();
gb.setPrettyPrinting();
gb.disableHtmlEscaping();
Gson gson = gb.create();
return gson.toJson(this);
}
}
显然,我剥离了所有处理逻辑,servlet 只是回显 JSON,这不是应用程序所做的,但可以说明这一点。在那个例子中,我可以在 HTTP Post 中抛出几乎任何字符串,但我只能得到有效的 Demo 对象。
如何在 node.js 中做这样的事情?
【问题讨论】:
标签: json node.js gson commonjs