一、导入依赖项
本文采用Jackson完成JSON的转换,因此要导入jackson相关的依赖项,创建Maven项目自动导入包。jackson依赖可从下列网址获得:http://mvnrepository.com/artifact/com.fasterxml.jackson.core/jackson-databind/2.9.6
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.7.3</version>
</dependency>
二、创建对象
创建TaskPath对象,接下来所有Json转换的对象都与该对象有关。
public class TaskPath {
private Integer X; //X坐标
private Integer Y; //Y坐标
private Integer Theta; //转角
public Integer getX() {
return X;
}
public void setX(Integer x) {
X = x;
}
public Integer getY() {
return Y;
}
public void setY(Integer y) {
Y = y;
}
public Integer getTheta() {
return Theta;
}
public void setTheta(Integer theta) {
Theta = theta;
}
}
三、创建测试程序,main函数
以下是Json和Java对象、List、Map的互相转换实现
public class JsonTest {
public static void main(String[] args) throws Exception {
ObjectMapper mapper = new ObjectMapper();
//Json转对象
String json="{\"x\":154,\"y\":24,\"theta\":14}";
TaskPath user = mapper.readValue(json, TaskPath.class);
System.out.println(user.getX()+" "+user.getY()+" "+user.getTheta());
//对象转Json
TaskPath taskPath1 = new TaskPath();
taskPath1.setX(123);
taskPath1.setY(345);
taskPath1.setTheta(15);
TaskPath taskPath2 = new TaskPath();
taskPath2.setX(12);
taskPath2.setY(34);
taskPath2.setTheta(15);
String string = mapper.writeValueAsString(taskPath1);
System.out.println(string);
//list转Json
List<TaskPath> list = new ArrayList<>();
list.add(taskPath1);
list.add(taskPath2);
String ljson = mapper.writeValueAsString(list);
System.out.println(ljson);
//Json转list
JavaType jt = mapper.getTypeFactory().constructParametricType(ArrayList.class, TaskPath.class);
List<TaskPath> urlist = mapper.readValue(ljson, jt);
for(int i = 0;i < urlist.size();i++)
{
System.out.println(urlist.get(i).getX()+" "+ urlist.get(i).getY()+" "+urlist.get(i).getTheta());
}
//Map转Json
HashMap<String, TaskPath> map = new HashMap<String, TaskPath>();
map.put("001", taskPath1);
map.put("002", taskPath2);
String mmjson = mapper.writeValueAsString(map);
System.out.println(mmjson);
//json转map
JavaType jvt = mapper.getTypeFactory().constructParametricType(HashMap.class,String.class,TaskPath.class);
Map<String,TaskPath> Map = mapper.readValue(mmjson, jvt);
Set<String> set = Map.keySet();
Iterator<String> it = set.iterator();
while(it.hasNext())
{
String str = it.next();
TaskPath path = Map.get(str);
System.out.println(str + ":"+path.getX()+" " + path.getY()+" " + path.getTheta());
}
}
}
实现结果如下:
154 24 14
{"x":123,"y":345,"theta":15}
[{"x":123,"y":345,"theta":15},{"x":12,"y":34,"theta":15}]
123 345 15
12 34 15
{"001":{"x":123,"y":345,"theta":15},"002":{"x":12,"y":34,"theta":15}}
001:123 345 15
002:12 34 15