2
回答
JSON大神来指教一下
注册华为云得mate10,2.9折抢先购!>>>   

有一个如下的Json串:

{"monthSelectBegin":["2017-01","2017-03"],"monthSelectEnd":["2017-01","2017-03"],"amortizeCounts":["1","1"],"amortizeAmounts":["1000","2000"]}

后台Java怎么去接收、封装?

或者,bean实体类怎么创建属性去封装?

在线等大神!!

 

举报
DreamMoon
发帖于11个月前 2回/134阅

请求怎么传的?直接传的话,创建个实体,属性包含monthSelectBegin,monthSelectEnd,amortizeCounts,amortizeAmounts和get set方法,即可,spring会自动封装进去

中括号[]表示里面这个数组,可用list 或 数组接收

public static void main(String[] args) {
		String str = "{\"monthSelectBegin\":[\"2017-01\",\"2017-03\"],\"monthSelectEnd\":[\"2017-01\",\"2017-03\"],\"amortizeCounts\":[\"1\",\"1\"],\"amortizeAmounts\":[\"1000\",\"2000\"]}";
		Gson gson = new Gson();
		A a = gson.fromJson(str, A.class);
		System.out.println(a.getMonthSelectBegin()[0]);
	}

class A {
		private String[] monthSelectBegin;
		private String[] monthSelectEnd;
		private String[] amortizeCounts;
		private String[] amortizeAmounts;

		public String[] getMonthSelectBegin() {
			return monthSelectBegin;
		}

		public void setMonthSelectBegin(String[] monthSelectBegin) {
			this.monthSelectBegin = monthSelectBegin;
		}

		public String[] getMonthSelectEnd() {
			return monthSelectEnd;
		}

		public void setMonthSelectEnd(String[] monthSelectEnd) {
			this.monthSelectEnd = monthSelectEnd;
		}

		public String[] getAmortizeCounts() {
			return amortizeCounts;
		}

		public void setAmortizeCounts(String[] amortizeCounts) {
			this.amortizeCounts = amortizeCounts;
		}

		public String[] getAmortizeAmounts() {
			return amortizeAmounts;
		}

		public void setAmortizeAmounts(String[] amortizeAmounts) {
			this.amortizeAmounts = amortizeAmounts;
		}
	}

后台接收,最简单字符串转bean

如果用springmvc,可用@RequestBody,json映射到目标实体,注意声明 consumes:application/json

顶部