如果您使用的是 Jackson,那么下面的简单示例对我有用。
定义 Foo 类:
public class Foo {
private List<String> fooElements = Arrays.asList("one", "two", "three");
public Foo() {
}
public List<String> getFooElements() {
return fooElements;
}
}
然后使用独立的 Java 应用程序:
import java.io.IOException;
import org.codehaus.jackson.JsonGenerationException;
import org.codehaus.jackson.map.JsonMappingException;
import org.codehaus.jackson.map.ObjectMapper;
public class JsonExample {
public static void main(String[] args) throws JsonGenerationException, JsonMappingException, IOException {
Foo foo = new Foo();
ObjectMapper mapper = new ObjectMapper();
System.out.println(mapper.writeValueAsString(foo));
}
}
输出:
{"fooElements":["one","two","three"]}