- 浏览: 2567076 次
- 性别:
- 来自: 成都
-
文章分类
最新评论
-
nation:
你好,在部署Mesos+Spark的运行环境时,出现一个现象, ...
Spark(4)Deal with Mesos -
sillycat:
AMAZON Relatedhttps://www.godad ...
AMAZON API Gateway(2)Client Side SSL with NGINX -
sillycat:
sudo usermod -aG docker ec2-use ...
Docker and VirtualBox(1)Set up Shared Disk for Virtual Box -
sillycat:
Every Half an Hour30 * * * * /u ...
Build Home NAS(3)Data Redundancy -
sillycat:
3 List the Cron Job I Have>c ...
Build Home NAS(3)Data Redundancy
Java Generate/Merge Files(5)Jackson and JSON
In java, we usually use jackson to convert JSON to string and string to JSON. I write a general class to support that.
pom.xml dependencies
<!-- JSON -->
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-core</artifactId>
<version>${jackson.version}</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-annotations</artifactId>
<version>${jackson.version}</version>
</dependency>
My major core java codes to do the converting
package com.j2c.feeds2g.services;
import java.io.IOException;
import com.fasterxml.jackson.core.JsonGenerationException;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.j2c.feeds2g.services.base.BaseService;
public class JSONMappingServiceJacksonImpl<T> extends BaseService implements JSONMappingService<T> {
private ObjectMapper jsonMapper;
public void init() {
jsonMapper = new ObjectMapper();
}
public T toJava(String json, Class<T> type) {
try {
return (T) jsonMapper.readValue(json, type);
} catch (JsonGenerationException e) {
logger.error("unmashall string [" + json + "] fail, exceptions: " , e);
} catch (JsonMappingException e) {
logger.error("unmashall string [" + json + "] fail, exceptions: " , e);
} catch (IOException e) {
logger.error("unmashall string [" + json + "] fail, exceptions: " , e);
}
return null;
}
public String toJSON(T objClass) {
try {
return jsonMapper.writeValueAsString(objClass);
} catch (JsonGenerationException e) {
logger.error("mashall object [" + objClass + "] fail, exceptions: " , e);
} catch (JsonMappingException e) {
logger.error("mashall object [" + objClass + "] fail, exceptions: " , e);
} catch (IOException e) {
logger.error("mashall object [" + objClass + "] fail, exceptions: " , e);
}
return null;
}
}
My unit tests
package com.j2c.feeds2g.services;
import java.io.File;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import org.apache.commons.io.FileUtils;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import com.j2c.feeds2g.models.Job;
import com.j2c.feeds2g.services.base.BaseService;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = { "classpath:test-context.xml" })
public class JsonMappingServiceTest extends BaseService {
@Autowired
@Qualifier("jsonMappingService")
private JSONMappingService<Job> jsonMappingService;
@Test
public void dummy() {
Assert.assertTrue(true);
}
@Test
public void json() throws IOException {
String jsonFile = FileUtils.readFileToString(new File(getFile("data/job.json")), StandardCharsets.UTF_8);
logger.trace("JsonFile content " + jsonFile);
Job job = jsonMappingService.toJava(jsonFile, Job.class);
Assert.assertNotNull(job);
logger.info("Job [" + job + "]");
logger.debug("cities [" + job.getCities() + "]");
logger.debug("stateIDs [" + job.getStateIDs() + "]");
logger.debug("posted [" + job.getPosted() + "]");
String decodeJson = jsonMappingService.toJSON(job);
Assert.assertNotNull(decodeJson);
logger.info("json " + decodeJson);
}
}
Some annotation in the POJO
@JsonProperty
private String action;
@JsonProperty("customer_id")
private Long customerID;
@JsonProperty
private DateTime posted;
@JsonProperty("industry_ids")
private List<Integer> industryIDs;
References:
http://websystique.com/java/json/jackson-json-annotations-example/
https://github.com/FasterXML/jackson-annotations
http://sillycat.iteye.com/blog/2119381
In java, we usually use jackson to convert JSON to string and string to JSON. I write a general class to support that.
pom.xml dependencies
<!-- JSON -->
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-core</artifactId>
<version>${jackson.version}</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-annotations</artifactId>
<version>${jackson.version}</version>
</dependency>
My major core java codes to do the converting
package com.j2c.feeds2g.services;
import java.io.IOException;
import com.fasterxml.jackson.core.JsonGenerationException;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.j2c.feeds2g.services.base.BaseService;
public class JSONMappingServiceJacksonImpl<T> extends BaseService implements JSONMappingService<T> {
private ObjectMapper jsonMapper;
public void init() {
jsonMapper = new ObjectMapper();
}
public T toJava(String json, Class<T> type) {
try {
return (T) jsonMapper.readValue(json, type);
} catch (JsonGenerationException e) {
logger.error("unmashall string [" + json + "] fail, exceptions: " , e);
} catch (JsonMappingException e) {
logger.error("unmashall string [" + json + "] fail, exceptions: " , e);
} catch (IOException e) {
logger.error("unmashall string [" + json + "] fail, exceptions: " , e);
}
return null;
}
public String toJSON(T objClass) {
try {
return jsonMapper.writeValueAsString(objClass);
} catch (JsonGenerationException e) {
logger.error("mashall object [" + objClass + "] fail, exceptions: " , e);
} catch (JsonMappingException e) {
logger.error("mashall object [" + objClass + "] fail, exceptions: " , e);
} catch (IOException e) {
logger.error("mashall object [" + objClass + "] fail, exceptions: " , e);
}
return null;
}
}
My unit tests
package com.j2c.feeds2g.services;
import java.io.File;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import org.apache.commons.io.FileUtils;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import com.j2c.feeds2g.models.Job;
import com.j2c.feeds2g.services.base.BaseService;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = { "classpath:test-context.xml" })
public class JsonMappingServiceTest extends BaseService {
@Autowired
@Qualifier("jsonMappingService")
private JSONMappingService<Job> jsonMappingService;
@Test
public void dummy() {
Assert.assertTrue(true);
}
@Test
public void json() throws IOException {
String jsonFile = FileUtils.readFileToString(new File(getFile("data/job.json")), StandardCharsets.UTF_8);
logger.trace("JsonFile content " + jsonFile);
Job job = jsonMappingService.toJava(jsonFile, Job.class);
Assert.assertNotNull(job);
logger.info("Job [" + job + "]");
logger.debug("cities [" + job.getCities() + "]");
logger.debug("stateIDs [" + job.getStateIDs() + "]");
logger.debug("posted [" + job.getPosted() + "]");
String decodeJson = jsonMappingService.toJSON(job);
Assert.assertNotNull(decodeJson);
logger.info("json " + decodeJson);
}
}
Some annotation in the POJO
@JsonProperty
private String action;
@JsonProperty("customer_id")
private Long customerID;
@JsonProperty
private DateTime posted;
@JsonProperty("industry_ids")
private List<Integer> industryIDs;
References:
http://websystique.com/java/json/jackson-json-annotations-example/
https://github.com/FasterXML/jackson-annotations
http://sillycat.iteye.com/blog/2119381
发表评论
-
Update Site will come soon
2021-06-02 04:10 1694I am still keep notes my tech n ... -
Portainer 2020(4)Deploy Nginx and Others
2020-03-20 12:06 439Portainer 2020(4)Deploy Nginx a ... -
Private Registry 2020(1)No auth in registry Nginx AUTH for UI
2020-03-18 00:56 449Private Registry 2020(1)No auth ... -
Docker Compose 2020(1)Installation and Basic
2020-03-15 08:10 392Docker Compose 2020(1)Installat ... -
VPN Server 2020(2)Docker on CentOS in Ubuntu
2020-03-02 08:04 475VPN Server 2020(2)Docker on Cen ... -
Nginx Deal with OPTIONS in HTTP Protocol
2020-02-15 01:33 373Nginx Deal with OPTIONS in HTTP ... -
PDF to HTML 2020(1)pdftohtml Linux tool or PDFBox
2020-01-29 07:37 435PDF to HTML 2020(1)pdftohtml Li ... -
Elasticsearch Cluster 2019(2)Kibana Issue or Upgrade
2020-01-12 03:25 743Elasticsearch Cluster 2019(2)Ki ... -
Spark Streaming 2020(1)Investigation
2020-01-08 07:19 307Spark Streaming 2020(1)Investig ... -
Hadoop Docker 2019 Version 3.2.1
2019-12-10 07:39 310Hadoop Docker 2019 Version 3.2. ... -
MongoDB 2019(3)Security and Auth
2019-11-16 06:48 254MongoDB 2019(3)Security and Aut ... -
MongoDB 2019(1)Install 4.2.1 Single and Cluster
2019-11-11 05:07 303MongoDB 2019(1) Follow this ht ... -
Monitor Tool 2019(1)Monit Installation and Usage
2019-10-17 08:22 336Monitor Tool 2019(1)Monit Insta ... -
Ansible 2019(1)Introduction and Installation on Ubuntu and CentOS
2019-10-12 06:15 326Ansible 2019(1)Introduction and ... -
Timezone and Time on All Servers and Docker Containers
2019-10-10 11:18 348Timezone and Time on All Server ... -
Kafka Cluster 2019(6) 3 Nodes Cluster on CentOS7
2019-10-05 23:28 298Kafka Cluster 2019(6) 3 Nodes C ... -
K8S Helm(1)Understand YAML and Kubectl Pod and Deployment
2019-10-01 01:21 343K8S Helm(1)Understand YAML and ... -
Rancher and k8s 2019(5)Private Registry
2019-09-27 03:25 382Rancher and k8s 2019(5)Private ... -
Jenkins 2019 Cluster(1)Version 2.194
2019-09-12 02:53 461Jenkins 2019 Cluster(1)Version ... -
Redis Cluster 2019(3)Redis Cluster on CentOS
2019-08-17 04:07 384Redis Cluster 2019(3)Redis Clus ...
相关推荐
5. **生成Schema**:调用Generator的`generateSchema()`方法,传入Bean的Class对象,得到Json Schema的JSON表示。 6. **处理结果**:将生成的JSON字符串保存为文件,或者直接用于API文档或其他验证目的。 示例代码...
Written by a MySQL Community Manager for Oracle, MySQL and JSON: A Practical Programming Guide shows how to quickly get started using JSON with MySQL and clearly explains the latest tools and ...
此外,还可以使用一些流行的Java库,如Gson、Jackson或Fastjson,它们提供了API来实现JSON与Java对象之间的转换。例如,使用Gson库可以这样操作: ```java Gson gson = new Gson(); User user = gson.fromJson(json...
Jackson是Java领域中广泛使用的JSON处理库,它提供了一套高效、灵活的API来解析、生成、序列化和反序列化JSON数据。Jackson-module-jsonSchema是Jackson生态中的一个附加模块,其主要功能是将Java对象转换为JSON ...
"GenerateKey.java"、"EncryptClasses.java"以及"Util"、"DecryptStart"这些标签暗示了这是一个关于Java加密和解密操作的项目。下面将详细讨论相关知识点。 1. **GenerateKey.java**: 这个文件很可能包含了生成...
标题中的“精品软件工具--Automatically generate model files, support JSON an.zip”暗示了一个软件工具,它能够自动地生成模型文件,并且支持JSON格式。这个工具可能是面向开发人员的,特别是那些在编程过程中...
解决 java.lang.RuntimeException: Could not generate DH keypair异常处理。 bcprov-ext-jdk15on-1.60、bcprov-jdk15on-1.60两个包放到jre下的$JAVA_HOME/jre/lib/ext的路径下,然后配置$JAVA_HOME/jre/lib/...
Automatically_generate_model_files,_support_JSON_a_PYJSONToModel
3. 使用`DBMS_JAVA.PRECOMPILE`或`DBMS_JAVA.GENERATE_JAR`存储过程将jar文件加载到JGA中。 4. 在PL/SQL代码中,通过`java.lang.Class.forName`加载所需类,并调用其方法进行JSON操作。 例如,一个简单的使用JSON...
ABAP JSON 字段名映射 name_mappings支持字段名大写,小写,驼峰等。 完整代码,可以直接运行。
这个强大的工具同样支持JSON格式,使得在Java应用程序中处理XML和JSON数据变得非常便捷。本篇文章将深入探讨xStream如何实现Java对象与XML和JSON的相互转换,并提供详细的代码示例。 ### 1. xStream的安装与引入 ...
JSON Generate 是一种基于 JSON 示例创建 go 结构的工具。 安装 $ go get github.com/calavera/json_generate 用法 在 go 代码中添加一个 JSON 示例作为常量。 就像是: const JSONExample_User = `{ "name": ...
3. **Java**: 在Java中,`org.json`库(如`org.json.JSONObject`和`org.json.JSONArray`)是常用的处理JSON数据的工具。此外,还有Gson和Jackson等第三方库,它们提供了更强大和灵活的JSON操作功能。 4. **PHP**: ...
Use it to compare and merge source code, web pages, XML and other text files with native application performance. Directly open and compare the text from Microsoft Office (Word and Excel), ...
yaml2json 该项目提供了一个简单的库和CLI,用于将YAML转换为JSON,分别用Python... generate some JSON...] | json2yaml# read from a file$ json2yaml foo.yaml动机某些程序和实用程序仅支持将JSON作为其配置输入格式
function string GenerateJson(dictionary dict) string jsonStr // 遍历字典并构建JSON字符串 for each key, value in dict jsonStr &= "{" & key & ": " & value & "}" end for return jsonStr end function...
在Java编程环境中,生成二维码(QR Code)是一项常见的任务,特别是在移动应用、网站链接分享、电子支付等领域。`QRCOdeUtil.java`文件显然包含了用于生成二维码的实用工具类。下面将详细介绍如何使用Java来生成...
json Generate Java types from JSON or JSON Schema and annotate those types for data-binding with Jackson, Gson, etc
Use it to compare and merge source code, web pages, XML and other text files with native application performance. Directly open and compare the text from Microsoft Office (Word and Excel), ...
// Generate JSON document dynamically using namespace std; using namespace jsonxx; Array a; a ; a ; a ; a ; a ; a ("key", "value"); Object o; o ; o ; o ; cout << o.json() ; To do Custom JSON ...