日期:2014-05-17  浏览次数:20890 次

jackson处理写出的json串如何赋值给String而不直接打印在控制台
我使用JsonGenerator来进行json的处理,但是json字符串直接打印在了控制台,想要将其赋值给String str都不行,想只有它有名没有类似objectMapper.writeValueAsString(bean);之类的方法。谢谢[code=Java][/code]
package com.hoo.test;

import java.io.IOException;

import org.codehaus.jackson.JsonEncoding;
import org.codehaus.jackson.JsonGenerationException;
import org.codehaus.jackson.JsonGenerator;
import org.codehaus.jackson.map.JsonMappingException;
import org.codehaus.jackson.map.ObjectMapper;

import com.hoo.entity.AccountBean;

public class Jackson {
public static void main(String[] args) throws JsonGenerationException, JsonMappingException, IOException {
AccountBean bean = new AccountBean();
bean.setAddress("China-Guangzhou");
bean.setEmail("liu.qiang@trs.com.cn");
bean.setId(1);
bean.setName("liuqiang");
ObjectMapper objectMapper = new ObjectMapper();
JsonGenerator jsonGenerator = objectMapper.getJsonFactory().createJsonGenerator(
System.out, JsonEncoding.UTF8);
jsonGenerator.writeObject(bean);


String str = objectMapper.writeValueAsString(bean);
System.out.println(str);
}
}


------解决方案--------------------
StringWriter writer =new StringWriter();

objectMapper.writeValue(writer, bean);

String str = writer.toString();

也就是把System.out 都换成 一个 StringWriter 就行了