我计划生成一个随机数,并使用json-simple
将其导出为JSON。我有以下代码
public class Main implements JSONAware{
private final int data;
public Main(int data){
this.data = data;
}
public String toJSONString(){
StringBuffer sb = new StringBuffer();
sb.append("[");
sb.append(data);
sb.append("]");
sb.append(",");
return sb.toString();
}
public static void main(String[] args){
JSONArray da = new JSONArray();
Random generator = new Random();
int [][] grid;
grid = new int[128][14];
for (int row = 0; row < 128; row++){
for (int col = 0; col < 14; col++){
grid[row][col] = generator.nextInt(100);
// da.add("%d",grid[row][col]);
da.add(grid[row][col]);
}
// System.out.println();
}
System.out.println(da);
}
打印如下:
[9,62,6,60,29,28,59,56,67,61,53,23,22,31,15,96,94,85,65,94,15,7,91,...]
但我试图将其打印为
[9,62,6,60,29,28,59,56,67,61,53,23,22,31,15,96,94,85,65,94,15,7,91,...],
[68,48,40,44,47,85,8,43,17,78,35,7,77,26,80,34,19,47,17,0,59,5,79,...],
.
.
.
任何人都可以告诉我如何从列中拆分行?
答案 0 :(得分:1)
据我了解你的问题,你想要128行是独立的JsonArray,即1行= 1 JsonArray。
为此你可以这样做:
public static void main(String[] args){
JSONArray jArray = new JSONArray();
Random generator = new Random();
int [][] grid;
grid = new int[128][14];
for (int row = 0; row < 128; row++){
JSONArray da = new JSONArray();
for (int col = 0; col < 14; col++){
grid[row][col] = generator.nextInt(100);
da.add(grid[row][col]);
}
jArray.add(da);
}
System.out.println(jArray);
}
答案 1 :(得分:0)
只需使用javaee提供的Json api即可。它很容易实现。您无需创建任何jsonToString(...)
。
import javax.json.Json;
import javax.json.JsonObject;
...
public static void main(String ...args) {
JsonObjectBuilder jsonBuilder = Json.createObjectBuilder();
Random generator = new Random();
int[][] grid;
grid = new int[128][14];
for (int row = 0; row < 128; row++) {
JsonArrayBuilder arrayBuilder = Json.createArrayBuilder();
for (int col = 0; col < 14; col++) {
grid[row][col] = generator.nextInt(100);
arrayBuilder.add(grid[row][col]);
}
jsonBuilder.add(Integer.toString(row), arrayBuilder.build());
}
JsonObject json = jsonBuilder.build();
System.out.println(json);
}
好吧,如果你不想使用javaee的json api ,请在你的代码中:
JSONObject obj=new JSONObject();
Random generator = new Random();
int [][] grid;
grid = new int[128][14];
for (int row = 0; row < 128; row++){
JSONArray da = new JSONArray();
for (int col = 0; col < 14; col++){
grid[row][col] = generator.nextInt(100);
da.add(grid[row][col]);
}
obj.put(Integer.toString(row), da);
}
System.out.println(obj);