【问题标题】:How do you return a JSON object from a Java Servlet如何从 Java Servlet 返回 JSON 对象
【发布时间】:2011-01-01 22:20:57
【问题描述】:

如何从 Java servlet 返回 JSON 对象。

以前在使用 servlet 进行 AJAX 时,我返回了一个字符串。是否需要使用 JSON 对象类型,或者您是否只返回一个看起来像 JSON 对象的字符串,例如

String objectToReturn = "{ key1: 'value1', key2: 'value2' }";

【问题讨论】:

  • 吹毛求疵;你不应该更喜欢{ key1: value1, key2: value2 }吗?
  • 吹毛求疵:他真正想要的是 { "key1": "value1", "key2": "value2" }... :-)
  • @Ankur 如果您决定使用 Spring 3.2.0,请查看 link
  • 吹毛求疵:我们不应该假设这些值是字符串,所以他真正想要的是 { "key1": value1, "key2": value2 }
  • 这些 Nitpicks(尤其是按此顺序)是史诗 :)

标签: java json servlets


【解决方案1】:

你可以像下面这样使用。

如果你想使用 json 数组:

  1. 下载 json-simple-1.1.1.jar 并添加到您的项目类路径中
  2. 创建一个名为 Model 的类,如下所示

    public class Model {
    
     private String id = "";
     private String name = "";
    
     //getter sertter here
    }
    
  3. 在 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();
      }
    
     }
    
  4. 输出

        [{"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

【讨论】:

    【解决方案2】:

    如何从 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());
    

    【讨论】:

    • 根据版本,JsonObject 是抽象的。我为较新的实现创建了一个答案。
    【解决方案3】:

    通过使用 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();
        }
    
      }
    }
    

    来自json response from servlet in java的帮助

    【讨论】:

      【解决方案4】:

      根据 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());
      }
      

      【讨论】:

        【解决方案5】:

        Close to BalusC 使用 Google Gson 库以 4 行简单的方式回答。将此行添加到 servlet 方法中:

        User objToSerialize = new User("Bill", "Gates");    
        ServletOutputStream outputStream = response.getOutputStream();
        
        response.setContentType("application/json;charset=UTF-8");
        outputStream.print(new Gson().toJson(objToSerialize));
        

        祝你好运!

        【讨论】:

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

          【讨论】:

            【解决方案7】:

            首先将 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);
            }
            

            就是这样。

            另见:

            【讨论】:

            • 我这样做是为了向 javascript 发送响应并在警报中显示响应。为什么它在警报中显示 html 代码..为什么我得到 html 代码作为响应。我做了和你说的一模一样的事情。
            • 我和@iLive 有同样的问题
            【解决方案8】:

            response.setContentType("text/json");

            //创建JSON字符串,我建议使用一些框架。

            String your_string;

            out.write(your_string.getBytes("UTF-8"));

            【讨论】:

            • 我需要使用 getBytes("UTF-8")) 还是只返回 String 变量?
            • 使用 UTF-8 编码 Web 应用程序的响应是一种安全的编程习惯。
            【解决方案9】:

            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);

            {"nombre":"juan","apellido":"machado","datosCriticos":[{"edad":12}]}

            如果你的 var 在使用 gson 时为空,则必须说人,它不会为你构建 json。只是

            {}

            【讨论】:

              【解决方案10】:

              为了方便 Java 编码,可能有一个 JSON 对象。但最后数据结构将被序列化为字符串。设置一个合适的 MIME 类型会很好。

              我建议 JSON Java 来自 json.org

              【讨论】:

              • 不正确。通常没有理由增加构造String 的开销——输出应该直接到OutputStream。或者,如果由于某种原因需要中间形式,可以使用byte[]。大多数 Java JSON 库都可以直接写入OutputStream
              【解决方案11】:

              将 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();
              

              【讨论】:

              • 这对我有帮助。正如 Mark Elliot 的回答中提到的, jsonObject 可能只是一个格式化为 json 的字符串。请记住使用双引号,因为单引号不会为您提供有效的 json。例如:String jsonStr = "{\"my_key\": \"my_value\"}";
              • 使用 response.setCharacterEncoding("utf-8");太
              【解决方案12】:

              只需将字符串写入输出流。如果您觉得有帮助,您可以将 MIME 类型设置为 text/javascripteditapplication/json 显然更正式)。 (有一个很小但非零的机会,它会阻止某天某天把事情搞砸,这是一个很好的做法。)

              【讨论】:

                【解决方案13】:

                我完全按照你的建议去做(返回 String)。

                不过,您可以考虑设置 MIME 类型以指示您正在返回 JSON(根据 this other stackoverflow post 它是“application/json”)。

                【讨论】:

                  猜你喜欢
                  • 2018-01-30
                  • 2015-02-02
                  • 1970-01-01
                  • 2018-01-07
                  • 1970-01-01
                  • 1970-01-01
                  • 2011-08-20
                  • 2012-03-27
                  • 2012-11-26
                  相关资源
                  最近更新 更多