如何从Java Servlet返回JSON对象

Ank*_*kur 149 java json servlets

如何从Java servlet返回JSON对象.

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

String objectToReturn = "{ key1: 'value1', key2: 'value2' }";
Run Code Online (Sandbox Code Playgroud)

use*_*924 171

将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();
Run Code Online (Sandbox Code Playgroud)

  • 这对我有帮助.正如Mark Elliot回答的那样,**jsonObject**可能只是一个格式化为json的字符串.请记住使用双引号,因为单引号不会为您提供有效的json.例如:`String jsonStr ="{\"my_key \":\"my_value \"}";` (7认同)
  • 使用response.setCharacterEncoding("utf-8")会很好; 太 (3认同)

Bal*_*usC 79

首先将JSON对象转换为String.然后将其写入响应编写器以及application/jsonUTF-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);
}
Run Code Online (Sandbox Code Playgroud)

就这样.

也可以看看:


Mar*_*iot 56

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

您可以考虑设置MIME类型以指示您正在返回JSON(根据此其他stackoverflow发布它的"application/json").


MAn*_*aik 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.addProperty("Mobile", 9999988888);
    json.addProperty("Name", "ManojSarnaik");

    // finally output the json string       
    out.print(json.toString());
Run Code Online (Sandbox Code Playgroud)


小智 8

只需在输出流中写一个字符串即可.如果您感觉有帮助,可以将MIME类型设置为text/javascript(编辑:application/json显然是官方).(有一个小但非零的机会,它会让某些东西不会弄乱它,这是一个很好的做法.)


sup*_*ser 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());
}
Run Code Online (Sandbox Code Playgroud)

}

    Bean bean = new Bean();
    Gson gson = new Gson();
    String json =gson.toJson(bean);
Run Code Online (Sandbox Code Playgroud)

的out.print(JSON);

{ "农布雷": "娟", "apellido": "马查多", "datosCriticos":[{ "EDAD":12}]}

不得不说人们,如果你的vars是空的,当使用gson它不会为你建立json.只是

{}


rav*_*iru 7

我使用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();
Run Code Online (Sandbox Code Playgroud)


nil*_*nil 6

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

我从json.org建议JSON Java.


Raf*_*ros 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());
}
Run Code Online (Sandbox Code Playgroud)