java中的多维数组到json(和返回)

rfbsl7qr  于 2021-07-03  发布在  Java
关注(0)|答案(1)|浏览(378)

我是java新手,但正在开发一个minecraft插件,我需要存储一些数据,并决定一个json将是最简单的,因为我将不容易访问数据库的插件。
我试图创建一个基本的json到(多维)数组,这样我就可以保存我的数据-但是所有合并最终都会附加到顶级的“areadata”选项卡上,并且不能正确地创建我要查找的数组。
下面是我正在尝试的部分代码,我想知道hashmap是否是一个好主意

import java.util.HashMap;

public class AreaHash {

    protected HashMap<String, String> AreaData = new HashMap<String, String>();

    public AreaHash(String name, String Owner, Integer X, Integer Y, Integer Z){
        AreaData.put("Name", name);
        AreaData.put("Owner", Owner);
        AreaData.put("X", X.toString());
        AreaData.put("Y", Y.toString());
        AreaData.put("Z", Z.toString());
    }
}
AreaHash RequestedArea = new AreaHash(Name, Owner.getUniqueId().toString(), location.getBlockX(), location.getBlockY(), location.getBlockZ());
String jsonString = new Gson().toJson(RequestedArea);
DataControl.UpdateJson("raid-areas.json", jsonString);

json输出

{
  "AreaHash": {
    "Name": "Test",
    "Owner": "gold",
    "X": "10",
    "Y": "15",
    "Z": "-1000"
  }, 
}

我想要生产的东西

{
  "1": [
    "Name": true,
    "Owner": "gold",
    "X": "10",
    "Y": "15",
    "Z": "-1000"
  ],
 "2": [
    "Name": true,
    "Owner": "silver",
    "X": "2110",
    "Y": "15",
    "Z": "-1200"
  ],
 "3": [
    "Name": true,
    "Owner": "test",
    "X": "-110",
    "Y": "70",
    "Z": "-1000"
  ],
}
ruarlubt

ruarlubt1#

您可以创建 AreaHash 对象,然后将其转换为json字符串。

Map<String, AreaHash> data = new HashMap<>();
data.put("1", new AreaHash(...));
data.put("2", new AreaHash(...));
data.put("3", new AreaHash(...));

String jsonString = new Gson().toJson(data);
System.out.println(jsonString);

输出(印刷精美)

{
  "1": {
    "Name": "Test",
    "Owner": "gold",
    "X": "10",
    "Y": "10",
    "Z": "0"
  },
  "2": {
    "Name": "Test",
    "Owner": "silver",
    "X": "10",
    "Y": "10",
    "Z": "-10"
  },
  "3": {
    "Name": "Test",
    "Owner": "test",
    "X": "10",
    "Y": "10",
    "Z": "-10"
  }
}

另外,请注意所需的输出不是有效的json。

[
  "Name": true,
  "Owner": "gold",
  "X": "10",
  "Y": "15",
  "Z": "-1000"
] // this will not parse

相关问题