首页 文章

如何从Java Servlet返回JSON对象

提问于
浏览
140

如何从Java servlet返回JSON对象 .

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

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

11 回答

  • 49

    我完全按照你的建议(返回 String ) .

    您可以考虑设置MIME类型以指示您正在返回JSON(根据this other stackoverflow post它是"application/json") .

  • 76

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

    首先将JSON对象转换为 String . 然后将其写入响应编写器以及 application/json 的内容类型和UTF-8的字符编码 .

    这里's an example assuming you'使用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);
    }
    

    就这样 .

    另见:

  • 8

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

    只需在输出流中写一个字符串即可 . 你可以将MIME类型设置为 text/javascripteditapplication/json 显然是官方的),如果你是一个很小但非零的机会,它是一个很好的做法 . )

  • 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); { “农布雷”: “娟”, “apellido”: “马查多”, “datosCriticos”:[{ “EDAD”:12}]}

    不得不说人们,如果你的vars是空的,当使用gson它不会为你 Build json . 就是这样

    {}

  • 25

    可能有一个JSON对象可以方便Java编码 . 但最后数据结构将序列化为字符串 . 设置正确的MIME类型会很好 .

    我建议从json.org JSON Java .

  • 163

    我使用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();
    
  • 3

    response.setContentType( “文本/ JSON”);

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

    String your_string;

    out.write(your_string.getBytes( “UTF-8”));

  • 6

    接近BalusC使用Google Gson lib在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

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

相关问题