有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java在2D数组中创建JSON以存储键值对

我有一个问题想请教你的专业知识。 我有类调用技术,我从数据库中检索数据作为技术类的对象列表technologyList= getProjectBD().getAllTechnology();

我的问题是如何将数据作为键值对存储在Json数组中。 这是我的密码

JSONArray technologyArray=new JSONArray();
for (Technology technology : technologyList) {
        JSONArray gridRow=new JSONArray();
        gridRow.put(technology.getTechnologyId());
        gridRow.put(technology.getTechnologyName());            
        technologyArray.put(gridRow);           
    }

我需要将此数据作为id和名称传递给jsp中的select选项。 例:-[1:JAVA,2:C#……]


共 (1) 个答案

  1. # 1 楼答案

    尝试使用如下com.google.gson.*元素:

    private JsonArray serializetechnologies(List<Technology> technologyList) {
        JsonArray jsonArray = new JsonArray();
        for (Technology technology : technologyList) {
            JsonObject jsonObject = new JsonObject();
            jsonObject.addProperty(technology.getTechnologyId()+"", technology.getTechnologyName());
            jsonArray.add(jsonObject);
        }
        return jsonArray;
    }
    

    如果您想获得价值:

    for (JsonElement jsonElement : jsonArray) {
        JsonObject jsonObject = (JsonObject) jsonElement;
        String name = jsonObject.get(technologyX.getTechnologyId() + "").getAsString();
        System.out.println("The name of technology witch Id = " + technologyX.getTechnologyId() + " is : "
                + name);
    }
    

    我希望这会有所帮助:)