java 从 POJO 生成 JSON 示例

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

Generate JSON sample from POJO

javajsonpojo

提问by fnCzar

We are looking for a way (maybe existing framework or similar) to generate sample JSON fragments based on POJOs (source or binary). For example:

我们正在寻找一种方法(可能是现有框架或类似框架)来生成基于 POJO(源代码或二进制文件)的示例 JSON 片段。例如:

public class foo {
   String var1;
   String var2;

   public String getVar1() { return var1; }
   public void setVar1(String var1) { this.var1 = var1; }

   public String getVar2() { return var2; }
   public void setVar2(String var2) { this.var2 = var2; }
}

would yield a JSON sample that could look like:

将产生一个 JSON 示例,可能如下所示:

{
  "var1": "string1",
  "var2": "string2"
}

any ideas? We could of course hand code that. Just looking to see if there is something already out there.

有任何想法吗?我们当然可以手动编码。只是想看看那里是否已经有东西。

回答by eugen

There is also another library called Genson http://code.google.com/p/genson/.

还有另一个名为 Genson http://code.google.com/p/genson/ 的库。

Actually Genson is faster and has more features than Gson and has performances close to Hymanson (but its a lot more lightweight) see http://code.google.com/p/genson/wiki/Metrics. It uses à streaming api instead of a dom model that brings better scalability and is nice in web applications where you can handle the conversion as the input arrives.

实际上,Genson 比 Gson 更快,功能更多,并且性能接近 Hymanson(但它更轻巧),请参见http://code.google.com/p/genson/wiki/Metrics。它使用 à 流 api 而不是 dom 模型,带来更好的可扩展性,并且在 Web 应用程序中很好,您可以在输入到达时处理转换。

Genson is well suited for all kind of use cases, ranging from simple conversion, to full customization of all the process. You can configure a lot of things (use fields and/or methods, use constructor with arguments and without any annotation, filter properties by visibility and a lot more). You should have a look at the wiki.

Genson 非常适合所有类型的用例,从简单的转换到所有流程的完全定制。您可以配置很多东西(使用字段和/或方法,使用带参数的构造函数并且没有任何注释,通过可见性过滤属性等等)。你应该看看维基。

Its latest version (0.91) is avaible in maven central repository.

其最新版本 (0.91) 可在 maven 中央存储库中使用。

<dependency>
    <groupId>com.owlike</groupId>
    <artifactId>genson</artifactId>
    <version>0.91</version>
</dependency>

Disclaimer: I'm the author of the library but I try to be objective (especially in the benchmarks).

免责声明:我是该库的作者,但我尽量保持客观(尤其是在基准测试中)。

EditA few words on Gson and Hymanson. I have used Hymanson for more than 2 years and a bit Gson. First thing to note is that Hymanson is the fastest json/java library out there (Gesnon tries to beat it but its quite hard). Hymanson has also a lot of features and configuration possibilities (most based on annotations). I had standard and advanced use of Hymanson, and it was nice until I needed features that Hymanson didn't provide. I found that the library was real hard to extend (for my use cases it was impossible without rewriting a big part).

编辑关于 Gson 和 Hymanson 的几句话。我已经使用 Hymanson 超过 2 年了,还有一点 Gson。首先要注意的是,Hymanson 是目前最快的 json/java 库(Gesnon 试图击败它,但它很难)。Hymanson 也有很多功能和配置可能性(大多数基于注释)。我对 Hymanson 有标准的和高级的使用,这很好,直到我需要 Hymanson 没有提供的功能。我发现这个库真的很难扩展(对于我的用例,不重写大部分是不可能的)。

I then tried Gson. First thing to note about Gson is that it does not use getter/setter but only fields! Its performances were not good (especially compared to Hymanson or Genson). With the latest versions it has improved as they also provide a streaming api, but its still not fast enough. At the begining its main advantage was good support of Java generics but Hymanson and Genson provide it too. Note also that Gson comes with less features out of the box than Genson or Hymanson. I also tried to implement the features I needed in Gson but I found that the Beans databinding part was not extensible (near everything in a single class with no extension points), so I would have to rewrite it. It was out of question and thats how I ended up with creating Genson.

然后我尝试了 Gson。关于 Gson 需要注意的第一件事是它不使用 getter/setter,而只使用字段!它的表现并不好(尤其是与Hyman逊或根森相比)。在最新版本中,它有所改进,因为它们还提供了流媒体 API,但仍然不够快。一开始,它的主要优势是对 Java 泛型的良好支持,但 Hymanson 和 Genson 也提供了它。另请注意,与 Genson 或 Hymanson 相比,Gson 的开箱即用功能更少。我还尝试在 Gson 中实现我需要的功能,但我发现 Beans 数据绑定部分是不可扩展的(在没有扩展点的单个类中几乎所有东西),所以我不得不重写它。这是毫无疑问的,这就是我最终创建 Genson 的方式。

If you don't want to use Genson, I really recommend you Hymanson over Gson.

如果您不想使用 Genson,我真的建议您使用 Hymanson 而不是 Gson。

回答by Philipp Reichart

You might also take a look at Gson(it directly reads/writes fields, no need for getters/setters):

你也可以看看Gson(它直接读/写字段,不需要 getter/setter):

Foo foo = ...
Gson gson = new Gson();
String json = gson.toJson(foo);

Do yourself a favor and don't hand-code JSON (or XML, or any structured data format if you can avoid it). It's unnecessarily reinventing the wheel. Someone has done it before and already solved escaping, nesting and all kinds of border cases for you.

帮自己一个忙,不要手动编码 JSON(或 XML,或任何可以避免的结构化数据格式)。这是不必要的重新发明轮子。之前有人做过,已经为你解决了逃逸、嵌套等各种边界情况。

回答by Reimeus

Using GSON:

使用GSON

Foo foo = new Foo();
foo.setVar1("string1");
foo.setVar2("string2");

Gson gson = new Gson();      
String json = gson.toJson(foo);

回答by bdoughan

Note:I'm the EclipseLink JAXB (MOXy)lead and a member of the JAXB (JSR-222)expert group.

注意:我是EclipseLink JAXB (MOXy) 的负责人,也是JAXB (JSR-222)专家组的成员。

You can use EclipseLink JAXB (MOXy)to convert your object model to JSON (and/or XML). Below is a complete example.

您可以使用EclipseLink JAXB (MOXy)将您的对象模型转换为 JSON(和/或 XML)。下面是一个完整的例子。

jaxb.properties

jaxb.properties

To specify MOXy as your JAXB provider you need to include a file called jaxb.propertiesin the same package as your domain model with the following entry (see: http://blog.bdoughan.com/2011/05/specifying-eclipselink-moxy-as-your.html).

要将 MOXy 指定为您的 JAXB 提供程序,您需要包含一个jaxb.properties在与域模型相同的包中调用的文件,其中包含以下条目(请参阅:http: //blog.bdoughan.com/2011/05/specifying-eclipselink-moxy-as -your.html)。

javax.xml.bind.context.factory=org.eclipse.persistence.jaxb.JAXBContextFactory

Demo

演示

The demo code below can be used to produce the JSON output from an instance of foo. Note how only the standard JAXB APIs are used. The JAXB APIs have been in the JDK/RE since Java SE 6.

下面的演示代码可用于从foo. 请注意如何仅使用标准 JAXB API。JAXB API 从 Java SE 6 开始就在 JDK/RE 中。

package forum12101023;

import javax.xml.bind.*;

public class Demo {

    public static void main(String[] args) throws Exception {
        JAXBContext jc = JAXBContext.newInstance(foo.class);

        foo foo = new foo();
        foo.setVar1("string1");
        foo.setVar2("string2");

        Marshaller marshaller = jc.createMarshaller();
        marshaller.setProperty("eclipselink.media-type", "application/json");
        marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
        marshaller.marshal(foo, System.out);
    }

}

Output

输出

{
   "var1" : "string1",
   "var2" : "string2"
}

For More Information

想要查询更多的信息

回答by DarkKnightFan

You can use Gson to do it.

你可以使用 Gson 来做到这一点。

Gson gson = new Gson();   
String fooJSON= gson.toJson(foo);  

Check thislink for a detail explanation also how to do it in JS/Extjs and also deserializing from JSON to POJO

检查链接以获取详细说明以及如何在 JS/Extjs 中执行此操作以及如何从 JSON 反序列化为 POJO