`
sillycat
  • 浏览: 2567076 次
  • 性别: Icon_minigender_1
  • 来自: 成都
社区版块
存档分类
最新评论

Java Generate/Merge Files(5)Jackson and JSON

    博客分类:
  • JAVA
 
阅读更多
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
分享到:
评论

相关推荐

    Java bean转换为Json Schema

    5. **生成Schema**:调用Generator的`generateSchema()`方法,传入Bean的Class对象,得到Json Schema的JSON表示。 6. **处理结果**:将生成的JSON字符串保存为文件,或者直接用于API文档或其他验证目的。 示例代码...

    MySQL and JSON A Practical Programming Guide 2018

    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 ...

    json格式转换为java实体类,idea导入即可

    此外,还可以使用一些流行的Java库,如Gson、Jackson或Fastjson,它们提供了API来实现JSON与Java对象之间的转换。例如,使用Gson库可以这样操作: ```java Gson gson = new Gson(); User user = gson.fromJson(json...

    jackson-module-jsonSchema-2.6.5.zip

    Jackson是Java领域中广泛使用的JSON处理库,它提供了一套高效、灵活的API来解析、生成、序列化和反序列化JSON数据。Jackson-module-jsonSchema是Jackson生态中的一个附加模块,其主要功能是将Java对象转换为JSON ...

    GenerateKey.java EncryptClasses.java

    "GenerateKey.java"、"EncryptClasses.java"以及"Util"、"DecryptStart"这些标签暗示了这是一个关于Java加密和解密操作的项目。下面将详细讨论相关知识点。 1. **GenerateKey.java**: 这个文件很可能包含了生成...

    精品软件工具--Automatically generate model files, support JSON an.zip

    标题中的“精品软件工具--Automatically generate model files, support JSON an.zip”暗示了一个软件工具,它能够自动地生成模型文件,并且支持JSON格式。这个工具可能是面向开发人员的,特别是那些在编程过程中...

    解决 java.lang.RuntimeException: Could not generate DH keypair异常处理所需的bcprov的jar

    解决 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_PYJSONTo

    Automatically_generate_model_files,_support_JSON_a_PYJSONToModel

    Oracle对JSON处理函数Jar包

    3. 使用`DBMS_JAVA.PRECOMPILE`或`DBMS_JAVA.GENERATE_JAR`存储过程将jar文件加载到JGA中。 4. 在PL/SQL代码中,通过`java.lang.Class.forName`加载所需类,并调用其方法进行JSON操作。 例如,一个简单的使用JSON...

    ABAP JSON 字段名映射 name_mappings 大写 小写 驼峰.txt

    ABAP JSON 字段名映射 name_mappings支持字段名大写,小写,驼峰等。 完整代码,可以直接运行。

    xStream转换xml和json源码

    这个强大的工具同样支持JSON格式,使得在Java应用程序中处理XML和JSON数据变得非常便捷。本篇文章将深入探讨xStream如何实现Java对象与XML和JSON的相互转换,并提供详细的代码示例。 ### 1. xStream的安装与引入 ...

    json_generate:基于 JSON 示例生成 go 结构体

    JSON Generate 是一种基于 JSON 示例创建 go 结构的工具。 安装 $ go get github.com/calavera/json_generate 用法 在 go 代码中添加一个 JSON 示例作为常量。 就像是: const JSONExample_User = `{ "name": ...

    json必须要用到的依赖包

    3. **Java**: 在Java中,`org.json`库(如`org.json.JSONObject`和`org.json.JSONArray`)是常用的处理JSON数据的工具。此外,还有Gson和Jackson等第三方库,它们提供了更强大和灵活的JSON操作功能。 4. **PHP**: ...

    Araxis Merge Professional 2012.4162 (x86/x64).part1

    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:将YAML转换为JSON的实用程序

    yaml2json 该项目提供了一个简单的库和CLI,用于将YAML转换为JSON,分别用Python... generate some JSON...] | json2yaml# read from a file$ json2yaml foo.yaml动机某些程序和实用程序仅支持将JSON作为其配置输入格式

    PB9生成和解析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生成二维码(qrcodeutil.java)

    在Java编程环境中,生成二维码(QR Code)是一项常见的任务,特别是在移动应用、网站链接分享、电子支付等领域。`QRCOdeUtil.java`文件显然包含了用于生成二维码的实用工具类。下面将详细介绍如何使用Java来生成...

    jsonschema.zip

    json Generate Java types from JSON or JSON Schema and annotate those types for data-binding with Jackson, Gson, etc

    Araxis Merge Professional 2012.4162 (x86/x64).part2

    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), ...

    A JSON parser in C++

    // 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 &lt;&lt; o.json() ; To do Custom JSON ...

Global site tag (gtag.js) - Google Analytics