如何漂亮地打印复杂的 Java 对象(例如,带有对象集合的字段)?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/43370772/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to pretty print a complex Java object (e.g. with fields that are collections of objects)?
提问by Steve Chambers
I'm looking for a library function (ideally from a commonly used framework e.g. Spring, Guava, Apache Commons etc.)that will nicely print the values of any Java object.
我正在寻找一个可以很好地打印任何 Java 对象值的库函数(最好来自常用框架,例如 Spring、Guava、Apache Commons 等)。
This is a general question rather than a specific one. Have seen similar questions on StackOverflow for which a common answer is "implement your own toString()
method on the class" but this option isn't always practical - am looking for a general way of doing this with any object I come across, which may originate from third party code. Another suggestion is to use RefectionToStringBuilderfrom Apache Commons, e.g:
这是一个笼统的问题,而不是一个具体的问题。在 StackOverflow 上看到过类似的问题,常见的答案是“toString()
在类上实现你自己的方法”,但这个选项并不总是实用 - 我正在寻找一种通用的方法来处理我遇到的任何对象,这可能源自第三方代码。另一个建议是使用Apache Commons 中的RefectionToStringBuilder,例如:
new ReflectionToStringBuilder(complexObject, new RecursiveToStringStyle()).toString()
But this has limited use - e.g. when it comes across a collection it tends to output something like this:
但这用途有限——例如,当它遇到一个集合时,它往往会输出如下内容:
java.util.ArrayList@fcc7ab1[size=1]
An actual use case example is to log an Iterable<PushResult>
returned from JGit's pushCommand.call()
method - if posting an answer please make sure it would work with this as well as any other complex object.
一个实际的用例示例是记录Iterable<PushResult>
从 JGit 的pushCommand.call()
方法返回的- 如果发布答案,请确保它可以与此以及任何其他复杂对象一起使用。
回答by Naxos84
You could try and use Gson. it also serializes Arrays, Maps or whatever....
您可以尝试使用 Gson。它还序列化数组、地图或其他任何东西....
MyObject myObject = new MyObject();
Gson gson = new GsonBuilder().setPrettyPrinting().serializeNulls().create();
gson.toJson(myObject);
For deserialization use:
对于反序列化使用:
gson.fromJson(MyObject.class);
For typed maps see this answer: Gson: Is there an easier way to serialize a map
对于类型化地图,请参阅此答案:Gson:是否有更简单的方法来序列化地图
回答by Sagar Trivedi
You can use the Hymanson ObjectMapper
class is use to bind data with json. you can use it like below:
您可以使用 HymansonObjectMapper
类将数据与 json 绑定。你可以像下面这样使用它:
ObjectMapper mapper = new ObjectMapper();
you can save json into object like below
您可以将json保存到如下所示的对象中
Object json = mapper.readValue(input,object.class);
you can write that in string variable
你可以把它写在字符串变量中
String prettyJson = mapper.writerWithDefaultPrettyPrinter().writeValueAsString(json);
it should work fine.
它应该可以正常工作。
回答by Jacob G.
One possible way to do this for any object without the use of an external library would be to use reflection of a generic type. In the following snippet, we simply access each field (including private fields) and print their name and value:
在不使用外部库的情况下对任何对象执行此操作的一种可能方法是使用泛型类型的反射。在以下代码段中,我们只需访问每个字段(包括私有字段)并打印它们的名称和值:
public static <T> String printObject(T t) {
StringBuilder sb = new StringBuilder();
for (Field field : t.getClass().getDeclaredFields()) {
field.setAccessible(true);
try {
sb.append(field.getName()).append(": ").append(field.get(t)).append('\n');
} catch (Exception e) {
e.printStackTrace();
}
}
return sb.toString();
}
This method could be placed in a utility class for easy access.
这个方法可以放在一个实用程序类中以便于访问。
If any of the object's fields do not override Object#toString
it will simply print the object's type and its hashCode.
如果对象的任何字段没有被覆盖Object#toString
,它将简单地打印对象的类型及其哈希码。
Example:
例子:
public class Test {
private int x = 5;
private int y = 10;
private List<List<Integer>> list = Arrays.asList(Arrays.asList(1, 2, 3), Arrays.asList(4, 5, 6));
}
>> printObject(new Test());
>>
>> x: 5
>> y: 10
>> list: [[1, 2, 3], [4, 5, 6]]
回答by Vijayakumar
You can use GSON
to convert your object to string. This will work for all the objects,
您可以使用GSON
将对象转换为字符串。这将适用于所有对象,
Gson gson = new Gson();
System.out.println(gson.toJson(objectYouWantToPrint).toString());
回答by assylias
You could use a JSON (or other format) mapper to pretty-print your object. It should handle most "standard" fields (primitives, strings, collections, maps, arrays etc.) and if it doesn't you can always add a custom serialiser.
您可以使用 JSON(或其他格式)映射器来漂亮地打印您的对象。它应该处理大多数“标准”字段(原语、字符串、集合、映射、数组等),如果不能,您始终可以添加自定义序列化程序。
For example, with Hymanson, it could be as simple as this:
例如,对于 Hymanson,它可以像这样简单:
public static void main(String... args) throws Exception {
ObjectMapper om = new ObjectMapper();
om.enable(SerializationFeature.INDENT_OUTPUT); //pretty print
String s = om.writeValueAsString(new Pojo());
System.out.println(s);
}
static class Pojo {
private int id = 1;
private List<String> list = Arrays.asList("A", "B");
//getters etc.
}
That code outputs:
该代码输出:
{
"id" : 1,
"list" : [ "A", "B" ]
}