您的位置 首页 java

使用Java将JSON转换为POJO

如果您有要映射到POJO而不需要编写完整的POJO类的JSON,则可以使用jsonschema2pojo库。这是一个出色的库,可以使用输入的JSON创建 Java 类。

使用Java将JSON转换为POJO

先决条件

程式语言 :Java

Pom依赖关系

<dependency>

<groupId>org. json schema2pojo</groupId>

<artifactId>jsonschema2pojo-core</artifactId>

<version>0.4.35</version>

</dependency>

程序

主要方法:

public static void main(String[] args) {

String packageName=”com.cooltrickshome”;

File inputJson= new File(“.”+File.separator+”input.json”);

File outputPojoDirectory=new File(“.”+File.separator+”convertedPojo”);

outputPojoDirectory.mkdirs();

try {

new JsonToPojo().convert2JSON(inputJson.toURI().toURL(), outputPojoDirectory, packageName, inputJson.getName().replace(“.json”, “”));

} catch (IOException e) {

// TODO Auto-generated catch block

System.out.println(“Encountered issue while converting to pojo: “+e. getMessage ());

e.printStackTrace();

}

}

怎么运行的

1. packageName定义输出POJO类的包名称。

2. inputJson定义了需要转换为POJO的JSON。

3. outputPojoDirectory是将在其中创建POJO文件的本地路径。

4. 我们调用创建的convert2JSON方法,传递输入JSON,输出路径,packageName和输出POJO类名。

convert2JSON方法:

public void convert2JSON(URL inputJson, File outputPojoDirectory, String packageName, String className) throws IOException{

JCodeModel codeModel = new JCodeModel();

URL source = inputJson;

GenerationConfig config = new DefaultGenerationConfig() {

@ Override

public boolean isGenerateBuilders() { // set config option by overriding method

return true;

}

public SourceType getSourceType(){

return SourceType.JSON;

}

};

SchemaMapper mapper = new SchemaMapper(new RuleFactory(config, new Jackson2Annotator(config), new SchemaStore()), new SchemaGenerator());

mapper.generate(codeModel, className, packageName, source);

codeModel.build(outputPojoDirectory);

}

怎么运行的

1.

我们创建一个JCodeModel对象,该对象将用于生成Java类。

2.

3.

我们定义了jsonschema2pojo的配置,该配置使程序知道输入源文件是JSON(getSourceType方法)。

4.

5.

现在,我们将配置以及在步骤1中创建的codeModel一起传递给schemamapper,后者将通过提供的JSON创建JavaType。

6.

7.

最后,我们调用build方法来创建输出类。

8.

完整程序

package com.cooltrickshome;

import java.io.File;

import java.io.IOException;

import java.net.MalformedURLException;

import java.net.URL;

import org.jsonschema2pojo.DefaultGenerationConfig;

import org.jsonschema2pojo.GenerationConfig;

import org.jsonschema2pojo.Jackson2Annotator;

import org.jsonschema2pojo.SchemaGenerator;

import org.jsonschema2pojo.SchemaMapper;

import org.jsonschema2pojo.SchemaStore;

import org.jsonschema2pojo.SourceType;

import org.jsonschema2pojo.rules.RuleFactory;

import com.sun.codemodel.JCodeModel;

public class JsonToPojo {

/**

* @param args

*/

public static void main(String[] args) {

String packageName=”com.cooltrickshome”;

File inputJson= new File(“.”+File.separator+”input.json”);

File outputPojoDirectory=new File(“.”+File.separator+”convertedPojo”);

outputPojoDirectory.mkdirs();

try {

new JsonToPojo().convert2JSON(inputJson.toURI().toURL(), outputPojoDirectory, packageName, inputJson.getName().replace(“.json”, “”));

} catch (IOException e) {

// TODO Auto-generated catch block

System.out.println(“Encountered issue while converting to pojo: “+e.getMessage());

e.printStackTrace();

}

}

public void convert2JSON(URL inputJson, File outputPojoDirectory, String packageName, String className) throws IOException{

JCodeModel codeModel = new JCodeModel();

URL source = inputJson;

GenerationConfig config = new DefaultGenerationConfig() {

@Override

public boolean isGenerateBuilders() { // set config option by overriding method

return true;

}

public SourceType getSourceType(){

return SourceType.JSON;

}

};

SchemaMapper mapper = new SchemaMapper(new RuleFactory(config, new Jackson2Annotator(config), new SchemaStore()), new SchemaGenerator());

mapper.generate(codeModel, className, packageName, source);

codeModel.build(outputPojoDirectory);

}

}

输入JSON:

{

“name”: “Virat”,

sport “: “cricket”,

“age”: 25,

“id”: 121,

“lastScores”: [

77,

72,

23,

57,

54,

36,

74,

17

]

}

生成的输出类:

package com.cooltrickshome;

import java.util.ArrayList;

import java.util.HashMap;

import java.util.List;

import java.util.Map;

import com.fasterxml.jackson. annotation .JsonAnyGetter;

import com.fasterxml.jackson.annotation.JsonAnySetter;

import com.fasterxml.jackson.annotation.JsonIgnore;

import com.fasterxml.jackson.annotation.JsonInclude;

import com.fasterxml.jackson.annotation.JsonProperty;

import com.fasterxml.jackson.annotation.JsonPropertyOrder;

import org.apache.commons.lang.builder.EqualsBuilder;

import org.apache.commons.lang.builder.HashCodeBuilder;

import org.apache.commons.lang.builder.ToStringBuilder;

@JsonInclude(JsonInclude.Include.NON_NULL)

@JsonPropertyOrder({

“name”,

“sport”,

“age”,

“id”,

“lastScores”

})

public class Input {

@JsonProperty(“name”)

private String name;

@JsonProperty(“sport”)

private String sport;

@JsonProperty(“age”)

private Integer age;

@JsonProperty(“id”)

private Integer id;

@JsonProperty(“lastScores”)

private List < Integer > lastScores = new ArrayList < Integer > ();

@JsonIgnore

private Map < String, Object > additionalProperties = new HashMap < String, Object > ();

@JsonProperty(“name”)

public String getName() {

return name;

}

@JsonProperty(“name”)

public void setName(String name) {

this.name = name;

}

public Input withName(String name) {

this.name = name;

return this;

}

@JsonProperty(“sport”)

public String getSport() {

return sport;

}

@JsonProperty(“sport”)

public void setSport(String sport) {

this.sport = sport;

}

public Input withSport(String sport) {

this.sport = sport;

return this;

}

@JsonProperty(“age”)

public Integer getAge() {

return age;

}

@JsonProperty(“age”)

public void setAge(Integer age) {

this.age = age;

}

public Input withAge(Integer age) {

this.age = age;

return this;

}

@JsonProperty(“id”)

public Integer getId() {

return id;

}

@JsonProperty(“id”)

public void setId(Integer id) {

this.id = id;

}

public Input withId(Integer id) {

this.id = id;

return this;

}

@JsonProperty(“lastScores”)

public List < Integer > getLastScores() {

return lastScores;

}

@JsonProperty(“lastScores”)

public void setLastScores(List < Integer > lastScores) {

this.lastScores = lastScores;

}

public Input withLastScores(List < Integer > lastScores) {

this.lastScores = lastScores;

return this;

}

@Override

public String toString() {

return ToStringBuilder.reflectionToString(this);

}

@JsonAnyGetter

public Map < String, Object > getAdditionalProperties() {

return this.additionalProperties;

}

@JsonAnySetter

public void setAdditionalProperty(String name, Object value) {

this.additionalProperties.put(name, value);

}

public Input withAdditionalProperty(String name, Object value) {

this.additionalProperties.put(name, value);

return this;

}

@Override

public int hashCode() {

return new HashCodeBuilder().append(name).append(sport).append(age).append(id).append(lastScores).append(additionalProperties).toHashCode();

}

@Override

public boolean equals(Object other) {

if (other == this) {

return true;

}

if ((other instanceof Input) == false) {

return false;

}

Input rhs = ((Input) other);

return new EqualsBuilder().append(name, rhs.name).append(sport, rhs.sport).append(age, rhs.age).append(id, rhs.id).append(lastScores, rhs.lastScores).append(additionalProperties, rhs.additionalProperties).isEquals();

}

}

最后,开发这么多年我也总结了一套学习Java的资料与面试题,如果你在技术上面想提升自己的话,可以关注我,私信发送领取资料或者在评论区留下自己的联系方式,有时间记得帮我点下转发让跟多的人看到哦。

使用Java将JSON转换为POJO

文章来源:智云一二三科技

文章标题:使用Java将JSON转换为POJO

文章地址:https://www.zhihuclub.com/185417.shtml

关于作者: 智云科技

热门文章

网站地图