【问题标题】:Create JSON in 2D array to store key value pair在二维数组中创建 JSON 以存储键值对
【发布时间】:2015-10-21 09:39:40
【问题描述】:

我有一个问题想请教您的专业知识。 我有类调用技术,我从数据库中检索数据作为技术类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);           
    }

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

【问题讨论】:

  • 为什么不在循环中使用 JSONObject 而不是 JSONArray?
  • 你显示正确的方式sir.Thanxx

标签: java arrays json


【解决方案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);
}

我希望这会有所帮助:)

【讨论】:

  • 我需要使用 js 先生访问值
  • 这个link很清楚的解释了JS和JSP的概念。
猜你喜欢
  • 2020-01-26
  • 2011-03-24
  • 1970-01-01
  • 2018-04-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-06-25
  • 1970-01-01
相关资源
最近更新 更多