hello_dakewang

导航

json:java中前台向后台传对象数据

前台传入的是一个json类型的数据,如何在后台解析成想要的数据类型?

例如:

  

后台获取了前台一个string类型的数据@RequestParam(value = "forceUpgradeTime") String forceUpgradeTime,
forceUpgradeTime的格式如下:

 

后台转换成我们需要的数据类型:

import org.json.JSONArray;//导入的是org.json
public List<Time> convertTime(
@RequestParam(value = "forceUpgradeTime") String forceUpgradeTime
) {
JSONArray jsonArray = new JSONArray(forceUpgradeTime);
List<Time> timeList = new ArrayList<>();
for(int i = 0; i<jsonArray.length(); i++) {
Time time = new Time();
time.setStartTime((String) jsonArray.getJSONObject(i).get("startTime"));
time.setEndTime((String) jsonArray.getJSONObject(i).get("endTime"));
time.setType((int) jsonArray.getJSONObject(i).get("type"));
timeList.add(time);
}
return timeList;
}


定义一个Time model类
public class Time {
private String startTime;
private String endTime;
private int type;
public Time(){}
public Time(String startTime, String endTime, int type) {
this.startTime = startTime;
this.endTime = endTime;
this.type = type;
}
public Time(String startTime, String endTime) {
this.startTime = startTime;
this.endTime = endTime;
}

public String getStartTime() {
return startTime;
}

public void setStartTime(String startTime) {
this.startTime = startTime;
}

public String getEndTime() {
return endTime;
}

public void setEndTime(String endTime) {
this.endTime = endTime;
}

public int getType() {
return type;
}

public void setType(int type) {
this.type = type;
}
}


posted on 2017-05-23 15:38  hello_dakewang  阅读(731)  评论(0编辑  收藏  举报