gpt4 book ai didi

java - 带数组列表的 JSON 响应

转载 作者:行者123 更新时间:2023-12-01 13:01:24 27 4
gpt4 key购买 nike

我是 JSON 和 jQuery 新手,我想使用 AJAX 获取 JSON 数据。我想使用提交按钮显示数据,我尝试这样做:

PrintWriter out = response.getWriter();
List<Countries> country = new ArrayList<Countries>();
country = FetchData.getAllCountries();
JSONObject js = new JSONObject();
JSONArray jsonArray = new JSONArray(country);

// set the response content-type
response.setContentType("application/json");

// writing the json-array to the output stream
out.print(jsonArray);
out.flush();

我收到编译时错误:The constructor JSONArray(List<Countries>) is undefined 。 下面的方式我尝试它工作,但我想使用杰森数组来实现

           PrintWriter out = response.getWriter();
ArrayList<Countries> country = new ArrayList<Countries>();
country = FetchData.getAllCountries();
String json = new Gson().toJson(country);
response.setContentType("application/json");
response.setCharacterEncoding("UTF-8");
out.write(json);

按以下方式工作

ArrayList<Countries> country=new ArrayList<Countries>();
country=FetchData.getAllCountries();
Gson gson = new Gson();
JsonElement element = gson.toJsonTree(country, new TypeToken<List<Countries>>() {}.getType());

JsonArray jsonArray = element.getAsJsonArray();
response.setContentType("application/json");
response.getWriter().print(jsonArray);

最佳答案

这是您正在使用的 json-simple 库吗?如果是:

PrintWriter out = response.getWriter();
List<Countries> country = new ArrayList<Countries>();
country = FetchData.getAllCountries();
JSONObject js = new JSONObject();
js.put("countries", country); // make sure the Country class overrides toString()

// set the response content-type
response.setContentType("application/json");

// writing the json-array to the output stream
out.print(js.toJSONString());
out.flush();

您似乎正在尝试将匿名数组插入到 json 字符串中。你不能这样做,它不是有效的 JSON。例如,您的 JSON 不能如下所示:

{
["1st Country", "2nd Country", "3rd Country"]
}

...JSON 中至少需要有一个键/值对,例如

{
"countries": ["1st Country", "2nd Country", "3rd Country"]
}

...所以“国家”是键,数组是值。如果您使用我上面给出的示例代码,那么您的服务器应该向浏览器返回一个 JSON 字符串,该字符串类似于上面的有效 JSON 示例。因此,如果您的客户端 javascript 使用像这样的 AJAX 调用来调用服务器(使用 jQuery):

$.ajax({
type: 'GET',
url: '/your-server-path',
dataType: 'json',
success: function(response, status, request) {
// jQuery automatically converts the JSON object to a Javascript object
for (int i=0; i<response.countries.length; i++) {
console.log("Country " + i + " is " + response.countries[i]);
}
},
error: function(request, status, error) {
console.log("Something went wrong...");
}
});

此外,正如我在第一个代码片段中提到的,您必须重写 Country 类的 toString() 方法,以便每个 Country code> 实例可以转换为字符串并添加到 JSON 数组中,例如

@Override
public String toString() {
// return some combination of variables in your Country class
// or however you want a Country to be represented
}

关于java - 带数组列表的 JSON 响应,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23489824/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com