在实现网络传输数据过程中,我们往往会遇到许多复杂的json数据,此时我们在接收数据的同时会转换为Java的对象进行数据整理,方便我们的数据处理等等
</pre><pre name="code" class="java"> private static JsonGenerator jsonGenerator = null;
private static ObjectMapper objectMapper = null;
static OutputStream out;
public static void init() {
objectMapper = new ObjectMapper();
try {
out = new ByteArrayOutputStream();
jsonGenerator = objectMapper.getJsonFactory().createJsonGenerator(
out, JsonEncoding.UTF8);
} catch (IOException e) {
e.printStackTrace();
}
}
public static void destory() {
try {
if (jsonGenerator != null) {
jsonGenerator.flush();
}
if (!jsonGenerator.isClosed()) {
jsonGenerator.close();
}
jsonGenerator = null;
objectMapper = null;
System.gc();
} catch (IOException e) {
e.printStackTrace();
}
}
public static String writeObject(Object o) throws JsonGenerationException,
IOException {
init();
jsonGenerator.writeObject(o);
out.toString();
destory();
return out.toString();
}
public static String writeObject(String str, Object o)
throws JsonGenerationException, IOException {
init();
jsonGenerator.writeStartObject();// {
jsonGenerator.writeObjectField(str, o);// user:{bean}
jsonGenerator.writeEndObject();// }
out.toString();
destory();
return out.toString();
}
public static <T> Object TowriteObject(String str, Class<T> o)
throws JsonGenerationException, IOException {
init();
Object obj=objectMapper.readValue(str, o);
destory();
return obj;
}json使用的jar包:
本文介绍了一种在Java中将复杂JSON数据转换为Java对象的方法,并提供了具体代码实现。通过对JSON数据的解析和序列化操作,使得在网络传输中处理JSON格式的数据变得更加便捷。
2856

被折叠的 条评论
为什么被折叠?



