这个示例将展示如何使用GSON和jackson将java对象转换为json。JSON是一种开放标准格式,它使用人类可读的文本来传输由属性-值对组成的数据对象。在设置中,我们将初始化一个平面列表,每个代码片段将使用该列表序列化为json。
class Plane {
private String planeType;
public Plane(String planeType) {
super();
this.planeType = planeType;
}
public String getPlaneType() {
return planeType;
}
@Override
public String toString() {
return Objects.toStringHelper(this).add("plane type: ", planeType).toString();
}
}
private List<Plane> planes = Lists.newArrayList();
private Plane seaPlane;
@Before
public void seedData () {
planes.add(new Plane("Commercial Transport Planes"));
planes.add(new Plane("General Aviation Planes"));
planes.add(new Plane("Military Planes"));
planes.add(new Plane("Sea Planes"));
planes.add(new Plane("Special Purpose Planes"));
seaPlane = new Plane("Sea Planes");
}
使用gson,这个代码段将把java对象转换为json。
@Test
public void marshall_java_object_to_json_with_gson () {
Gson gson = new Gson();
String json = gson.toJson(seaPlane);
logger.info(json);
assertEquals(JSON_OBJECT, json);
}
输出
{
"planeType":"Sea Planes"
}
这个代码片段将使用GSON将java列表转换为json数组。
@Test
public void marshall_java_list_to_json_with_gson () {
Gson gson = new Gson();
String json = gson.toJson(planes);
logger.info(json);
assertEquals(JSON_ARRAY, json);
}
输出
[
{
"planeType":"Commercial Transport Planes"
},
{
"planeType":"General Aviation Planes"
},
{
"planeType":"Military Planes"
},
{
"planeType":"Sea Planes"
},
{
"planeType":"Special Purpose Planes"
}
]
这个代码段将通过调用ObjectMapper使用jackson将对象转换为json。writeValueAsString,它将java对象序列化为JSON字符串。
@Test
public void marshall_java_object_to_json_with_jackson () throws JsonProcessingException {
ObjectMapper objectMapper = new ObjectMapper();
String json = objectMapper.writeValueAsString(seaPlane);
logger.info(json);
assertEquals(JSON_OBJECT, json);
}
输出
{
"planeType":"Sea Planes"
}
此代码段将使用Jackson将ArrayList转换为JSON。
@Test
public void marshall_java_list_to_json_with_jackson () throws JsonProcessingException {
ObjectMapper objectMapper = new ObjectMapper();
String json = objectMapper.writeValueAsString(planes);
logger.info(json);
assertEquals(JSON_ARRAY, json);
}
输出
[
{
"planeType":"Commercial Transport Planes"
},
{
"planeType":"General Aviation Planes"
},
{
"planeType":"Military Planes"
},
{
"planeType":"Sea Planes"
},
{
"planeType":"Special Purpose Planes"
}
]
版权说明 : 本文为转载文章, 版权归原作者所有 版权申明
原文链接 : http://www.leveluplunch.com/java/examples/convert-java-object-to-from-json/
内容来源于网络,如有侵权,请联系作者删除!