如何从Java servlet返回JSON对象。
以前使用servlet进行AJAX时,我返回了一个字符串。是否存在需要使用的JSON对象类型,或者只返回看起来像JSON对象的String,例如
String objectToReturn = "{ key1: 'value1', key2: 'value2' }";
答案 0 :(得分:168)
将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();
答案 1 :(得分:79)
首先将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);
}
就是这样。
答案 2 :(得分:55)
我完全按照你的建议(返回String
)。
您可以考虑设置MIME类型以指示您正在返回JSON(根据this other stackoverflow post它是“application / json”)。
答案 3 :(得分:28)
如何从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.put("Mobile", 9999988888);
json.put("Name", "ManojSarnaik");
// finally output the json string
out.print(json.toString());
答案 4 :(得分:8)
只需在输出流中写一个字符串即可。如果您感觉有帮助,可以将MIME类型设置为text/javascript
(编辑:application/json
显然是官方的)。 (有一个小但非零的机会,它会让某些东西不会弄乱它,这是一个很好的做法。)
答案 5 :(得分:8)
Gson对此非常有用。更容易均匀。 这是我的例子:
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);
{&#34; NOMBRE&#34;:&#34;胡安&#34;&#34; apellido&#34;:&#34;马查多&#34;&#34; datosCriticos&#34;:[ {&#34; EDAD&#34; 12}]}
不得不说人们如果使用gson时你的vars是空的它不会为你构建json。只是
{}
答案 6 :(得分:6)
答案 7 :(得分:6)
我使用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();
答案 8 :(得分:4)
JsonObject
是抽象的,具体取决于Java版本(或JDK,SDK,JRE ...,对Java生态系统来说是新的)。因此,这是一个新的实现:
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());
}
答案 9 :(得分:3)
response.setContentType( “文本/ JSON”);
//创建JSON字符串,我建议使用一些框架。
字符串your_string;
out.write(your_string.getBytes( “UTF-8”));
答案 10 :(得分:1)
您可以像下面这样使用波纹管。
如果要使用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
答案 11 :(得分:0)
使用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));
祝你好运!
答案 12 :(得分:0)
通过使用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();
}
}
}