如何从Java servlet返回JSON对象。
以前,当使用servlet执行AJAX时,我返回了一个字符串。是否有需要使用的JSON对象类型,或者您只是返回了一个看起来像JSON对象的String,例如
String objectToReturn = "{ key1: 'value1', key2: 'value2' }";
如何从Java servlet返回JSON对象。
以前,当使用servlet执行AJAX时,我返回了一个字符串。是否有需要使用的JSON对象类型,或者您只是返回了一个看起来像JSON对象的String,例如
String objectToReturn = "{ key1: 'value1', key2: 'value2' }";
Answers:
我完全按照您的建议(返回String
)进行操作。
不过,您可能会考虑将MIME类型设置为指示您正在返回JSON(根据其他stackoverflow文章,其为“ application / json”)。
将JSON对象写入响应对象的输出流。
您还应该按如下所示设置内容类型,这将指定您要返回的内容:
response.setContentType("application/json");
// Get the printwriter object from response to write the required json object to the output stream
PrintWriter out = response.getWriter();
// Assuming your json object is **jsonObject**, perform the following, it will return your json object
out.print(jsonObject);
out.flush();
String jsonStr = "{\"my_key\": \"my_value\"}";
首先将JSON对象转换为String
。然后将其与application/json
UTF-8的内容类型和字符编码一起写到响应编写器中。
这是一个示例,假设您使用Google Gson将Java对象转换为JSON字符串:
protected void doXxx(HttpServletRequest request, HttpServletResponse response) {
// ...
String json = new Gson().toJson(someObject);
response.setContentType("application/json");
response.setCharacterEncoding("UTF-8");
response.getWriter().write(json);
}
就这样。
如何从Java Servlet返回JSON对象
response.setContentType("application/json");
response.setCharacterEncoding("utf-8");
PrintWriter out = response.getWriter();
//create Json Object
JsonObject json = new JsonObject();
// put some value pairs into the JSON object .
json.addProperty("Mobile", 9999988888);
json.addProperty("Name", "ManojSarnaik");
// finally output the json string
out.print(json.toString());
只需将字符串写入输出流即可。如果您觉得有帮助,可以将MIME类型设置为text/javascript
(edit:application/json
显然是正式的)。(这有很小的机会,但是有零的机会,它可以防止某天弄乱它,这是一个好习惯。)
格森对此非常有用。甚至更容易。这是我的例子:
public class Bean {
private String nombre="juan";
private String apellido="machado";
private List<InnerBean> datosCriticos;
class InnerBean
{
private int edad=12;
}
public Bean() {
datosCriticos = new ArrayList<>();
datosCriticos.add(new InnerBean());
}
}
Bean bean = new Bean();
Gson gson = new Gson();
String json =gson.toJson(bean);
out.print(json);
{“ nombre”:“ juan”,“ apellido”:“ machado”,“ datosCriticos”:[{“ edad”:12}]}
不得不说别人,如果使用gson时您的var是空的,它将不会为您构建json。
{}
我使用Jackson将Java Object转换为JSON字符串并发送如下。
PrintWriter out = response.getWriter();
ObjectMapper objectMapper= new ObjectMapper();
String jsonString = objectMapper.writeValueAsString(MyObject);
response.setContentType("application/json");
response.setCharacterEncoding("UTF-8");
out.print(jsonString);
out.flush();
为方便Java编码,可能有一个JSON对象。但是最后,数据结构将被序列化为字符串。设置适当的MIME类型会很好。
我建议使用json.org中的JSON Java。
String
-输出的开销OutputStream
。或者,如果出于某种原因需要中间形式,可以使用byte[]
。大多数Java JSON库都可以直接写入OutputStream
。
取决于Java版本(或JDK,SDK,JRE ...不知道,对Java生态系统JsonObject
是新的),它是抽象的。因此,这是一个新的实现:
import javax.json.Json;
import javax.json.JsonObject;
...
try (PrintWriter out = response.getWriter()) {
response.setContentType("application/json");
response.setCharacterEncoding("UTF-8");
JsonObject json = Json.createObjectBuilder().add("foo", "bar").build();
out.print(json.toString());
}
使用Google Gson lib在4条简单的代码行中接近BalusC答案。将此行添加到servlet方法中:
User objToSerialize = new User("Bill", "Gates");
ServletOutputStream outputStream = response.getOutputStream();
response.setContentType("application/json;charset=UTF-8");
outputStream.print(new Gson().toJson(objToSerialize));
祝好运!
通过使用Gson,您可以发送json响应,请参见以下代码
您可以看到此代码
@WebServlet(urlPatterns = {"/jsonResponse"})
public class JsonResponse extends HttpServlet {
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("application/json");
response.setCharacterEncoding("utf-8");
Student student = new Student(12, "Ram Kumar", "Male", "1234565678");
Subject subject1 = new Subject(1, "Computer Fundamentals");
Subject subject2 = new Subject(2, "Computer Graphics");
Subject subject3 = new Subject(3, "Data Structures");
Set subjects = new HashSet();
subjects.add(subject1);
subjects.add(subject2);
subjects.add(subject3);
student.setSubjects(subjects);
Address address = new Address(1, "Street 23 NN West ", "Bhilai", "Chhattisgarh", "India");
student.setAddress(address);
Gson gson = new Gson();
String jsonData = gson.toJson(student);
PrintWriter out = response.getWriter();
try {
out.println(jsonData);
} finally {
out.close();
}
}
}
来自Java中servlet的json响应很有帮助
您可以像下面这样使用波纹管。
如果要使用json数组:
创建一个名为Model的类,例如波纹管
public class Model {
private String id = "";
private String name = "";
//getter sertter here
}
在sevlet getMethod中,您可以像下面这样使用
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
//begin get data from databse or other source
List<Model> list = new ArrayList<>();
Model model = new Model();
model.setId("101");
model.setName("Enamul Haque");
list.add(model);
Model model1 = new Model();
model1.setId("102");
model1.setName("Md Mohsin");
list.add(model1);
//End get data from databse or other source
try {
JSONArray ja = new JSONArray();
for (Model m : list) {
JSONObject jSONObject = new JSONObject();
jSONObject.put("id", m.getId());
jSONObject.put("name", m.getName());
ja.add(jSONObject);
}
System.out.println(" json ja = " + ja);
response.addHeader("Access-Control-Allow-Origin", "*");
response.setContentType("application/json");
response.setCharacterEncoding("UTF-8");
response.getWriter().print(ja.toString());
response.getWriter().flush();
} catch (Exception e) {
e.printStackTrace();
}
}
输出:
[{"name":"Enamul Haque","id":"101"},{"name":"Md Mohsin","id":"102"}]
我你想JSON对象就像这样使用:
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
try {
JSONObject json = new JSONObject();
json.put("id", "108");
json.put("name", "Enamul Haque");
System.out.println(" json JSONObject= " + json);
response.addHeader("Access-Control-Allow-Origin", "*");
response.setContentType("application/json");
response.setCharacterEncoding("UTF-8");
response.getWriter().print(json.toString());
response.getWriter().flush();
// System.out.println("Response Completed... ");
} catch (Exception e) {
e.printStackTrace();
}
}
以上功能输出:
{"name":"Enamul Haque","id":"108"}
完整的源代码提供给GitHub:https://github.com/enamul95/ServeletJson.git
{ key1: value1, key2: value2 }
吗?