java 使用带有对象的 GSON 打印 JSON 对象

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10823118/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-31 02:44:36  来源:igfitidea点击:

Using GSON with object to print JSON object

javajsongson

提问by user82302124

Quick questions about GSON, after reading the documentation. This is what I have with JSON:

阅读文档后有关 GSON 的快速问题。这就是我对 JSON 的看法:

var json = { 
     id: "person1", 
     name: "person 1", 
     data: {"email": "[email protected]"},
     children: [{
                    id: "person2",
                    name: "person 2",
                    data: {"email": "[email protected]"},
                    children: []
                },{
                    id: "person3",
                    name: "person 3",
                    data: {"email": "[email protected]"},
                    children: []
                }
                ] 
} 

1) Can I use GSON without using Class objects in Java? Can this be done easily using GSON and Java. Meaning I can do something like

1) 我可以在不使用 Java 类对象的情况下使用 GSON 吗?这可以使用 GSON 和 Java 轻松完成吗?意思是我可以做类似的事情

GSON gson = new GSON();
gson.toJson("name", "person 1");

2) When I use this example:

2)当我使用这个例子时:

            Gson gson = new Gson();
            Person p = new Contact(rs.getString("name"));
            gson.toJson(p);
            String json = gson.toString();
            System.out.println(json);

My Json output is not what I expected. That Person instance is a public class instance with just one property - name (for testing purposes). Why would I see essentially Factory, serializeNulls, etc in the output?

我的 Json 输出不是我所期望的。该 Person 实例是一个公共类实例,只有一个属性 - 名称(用于测试目的)。为什么我会在输出中基本上看到 Factory、serializeNulls 等?

Thanks

谢谢

回答by Jesse Wilson

Replace this:

替换这个:

gson.toJson(p);
String json = gson.toString();

with this:

有了这个:

String json = gson.toJson(p);