对象和json字符串互转

一,需要jar(注:这里是json字符串,不是json对象,json对象可能引入其他的jar包)。

  1. gson-2.8.0.jar

二、java对象和json字符串互转代码如下。

	public static void main(String[] args) {
		MainInfo model = new MainInfo();
		model.setRequestId("1234567890");
		Account account = new Account();
		account.setAccountId("10001");
		account.setAccountCode("10001x");
		account.setValidTime("2018-10-25 11:11:11");
		List<Account> accountList = new ArrayList<Account>();
		accountList.add(account);
		model.setAccountList(accountList);
		//对象转换为json字符串
		String jsonStr = new GsonBuilder().create().toJson(model);
		System.out.println(jsonStr);
		//json字符串转换为对象
		MainInfo newModel= (MainInfo)new GsonBuilder()
				.create().fromJson(jsonStr, MainInfo.class);
		System.out.println(newModel.toString());
	}

三、数组对象和json数组字符串互转代码如下。

	public static void main(String[] args) {
		List<MainInfo> list = new ArrayList<MainInfo>();
		MainInfo model = new MainInfo();
		model.setRequestId("1234567890");
		Account account = new Account();
		account.setAccountId("10001");
		account.setAccountCode("10001x");
		account.setValidTime("2018-10-25 11:11:11");
		List<Account> accountList = new ArrayList<Account>();
		accountList.add(account);
		model.setAccountList(accountList);
		list.add(model);
		list.add(model);
		//数组对象转换为json字符串
		String jsonArrStr = new GsonBuilder().create().toJson(list);
		System.out.println(jsonArrStr);
		//json字符串转换为数组对象
		MainInfo[] modelArr = (MainInfo[])new GsonBuilder()
				.create().fromJson(jsonArrStr, MainInfo[].class);
		for (MainInfo mainInfo : modelArr) {
			System.out.println(mainInfo.toString());
		}
	}
	}

你可能感兴趣的:(代码)