java生成json测试数据

利用gson和IOutils的jar包生成测试数据:

首先,导入jar包,关于jar包可以用maven管理工具,可以直接百度下载jar包;

json测试数据的代码:


package createtestjsondata;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.HashSet;
import java.util.List;
import java.util.Random;
import org.apache.commons.io.IOUtils;
import org.junit.Test;
import com.google.gson.JsonArray;
import com.google.gson.JsonObject;

public class TestMixStudentJson {
	@Test
	@SuppressWarnings("deprecation")
	public void fun() throws FileNotFoundException, IOException {
		long startTime=System.currentTimeMillis();
		String pathname="D:\\Mixdata.json";
	    File file=new File(pathname);
	    if(file.exists()){
	    	file.delete();
	    }
		for(int i=1;i<11;i++){
			generateStudentJsonData(i,file);
		}
		long endTime=System.currentTimeMillis();
		System.out.println("生成测试数据完成!");
		System.out.println("程序运行了多长时间:"+(endTime-startTime)+"毫秒");
	}

	public void generateStudentJsonData(int i,File f) throws IOException, IOException {
		JsonObject object = new JsonObject();
		object.addProperty("ResourceID", "CY");
		object.addProperty("AnswerNum", i);
		object.addProperty("StandardScore", 2);

		JsonArray array = new JsonArray();
		Random random=new Random();
		int j=random.nextInt(10)+40;
		setStudentDataArrays(array,j);
		object.add("StudentData", array);
        String jsonData=object.toString().replaceAll("\"", "\'");
        jsonData=jsonData+"|10;";
		IOUtils.write(jsonData+"\r\n",new FileOutputStream(f,true));
		//System.out.print(object.toString().replaceAll("\"", "\'"));	       
	}

	// 在一个数据里面添加
	public void setStudentDataArrays(JsonArray array,int j) {
		for (int i = 1; i < j; i++) {
			JsonObject StudentDataArrays = new JsonObject();
			// int randomI = getRandomArrays(10, 20)[i - 1];
			List<String> list = TestReadFile.getStringList();
			List<String> newList = TestReadFile.createRandomList(list, 501);
			String stringName = newList.get(i);
			// String stringName = "basestu" + randomI;
			StudentDataArrays.addProperty("StudentID", stringName);
			String answerString = pickRandom();
			StudentDataArrays.addProperty("Answer", answerString);
			array.add(StudentDataArrays);
		}
	}

	// 获取一个数组中任意的一个元素
	private String pickRandom() {
		String[] array = { "AB", "BCD", "ACD", "ADC", "BCD", "CAD", "CD",
				"ABCD", "EBC" };
		int length = array.length;
		Random random = new Random();
		return array[random.nextInt(length)];
	}
}

运动结果:

生成测试数据完成!
程序运行了多长时间:321毫秒

关于整个代码运行过程:

1.先生成sjon数据

2.然后把json数据合并到一起

3.最后把json数据利用IOutils包写入到文本文件之中

猜你喜欢

转载自blog.csdn.net/zy345293721/article/details/81227511
今日推荐