[英]How to convert a Java object to JSON object in Eclipse
My requirement is to convert a plain Java object to JSON format - 我的要求是将普通的Java对象转换为JSON格式-
The Java object has following format - Java对象具有以下格式-
Record Id: 168349200
Name: jane
City: abababa
State: ababab
Insertion Date: 18/04/2017 10:16:17
I have gone through some tutorials and found that GSON library is a way to do it. 我浏览了一些教程,发现GSON库是一种实现方法。 I tried to install the gson jar in my Eclipse project (using Eclipse Mars Release (4.5.0)).
我试图在我的Eclipse项目中安装gson jar(使用Eclipse Mars Release(4.5.0))。
But when I do - 但是当我这样做时
import com.google.gson.Gson
in the class where I want to do the conversion of the Java object to JSON it throws an exception. 在我想将Java对象转换为JSON的类中,它将引发异常。
I think I have not added the GSON jar file properly. 我想我还没有正确添加GSON jar文件。
Can some one please help. 有人可以帮忙吗?
Thanks. 谢谢。
Try: 尝试:
Gson gson = new Gson();
String jsonString = null;
try {
jsonString = gson.toJson(javaObject);
} catch (Exception e) {
e.printStackTrace();
}
From Java Object to Json using ObjectMapper: 使用ObjectMapper从Java Object到Json:
ObjectMapper objMapper = new ObjectMapper().setSerializationInclusion(Include.NON_NULL);
MyObject mObject = new MyObject();
String jsonObject ="";
mObject.setField1(value1);
mObject.setField2(value2);
mObject.setField3(value3);
try {
jsonObject = objMapper.writeValueAsString(mObject);
System.out.println(jsonObject); //You can then store it in a file
} catch (JsonProcessingException e) {
e.printStackTrace();
}
You should add these imports: 您应该添加以下导入:
import com.fasterxml.jackson.annotation.JsonInclude.Include;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
And in the pom.xml these lines: 在pom.xml中的这些行:
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-core</artifactId>
<version>2.7.5</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-annotations</artifactId>
<version>2.7.5</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.7.5</version>
</dependency>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.