Home  >  Article  >  Java  >  How to return json in java

How to return json in java

(*-*)浩
(*-*)浩Original
2019-05-15 16:48:259655browse

This article will introduce how to write a Java program to return Json data. This time, it will be introduced in three ways.

Recommended course: Java tutorial

How to return json in java

Java method to return json:

Method 1: Of course, type all the code by hand to return json data.

Requires HttpHttpServletRequest request HttpServletResponse response

Backend:

@RequestMapping(value="/haha")
 
public void xxx (HttpHttpServletRequest request,HttpServletResponse response)
{     JSONObject json =new JSONObject();
      json.put("result"," success")
      response.setCharacterEncoding("utf-8");
response.setContentType("application/json;charset=utf-8");
      PrintWriter out = null;
      out = response.getWriter();
      out.write(json.toString()); 
}

Front-end:

$.ajax({
data : {
// userNameOrTel: $("#user").val(),
// password: $("#pwd").val()
},
type : "post",  
url : "admin/login/",
dataType : "json",
contentType : "application/json;charset=utf-8", 
async : false,  //同步 异步
success : function(data) {
    debugger; 
}
}
});

Method 2: @ResponseBody Annotation

Backend:

@ResponseBody 
@RequestMapping(value="/haha")
public Msg xxx (){  return msg }

Front-end:

$.ajax({
data : {
// userNameOrTel: $("#user").val(),
// password: $("#pwd").val()
},
type : "post",  
url : "admin/login/",
dataType : "json",
contentType : "application/json;charset=utf-8", 
async : false,  //同步 异步
success : function(data) {
    debugger; 
}
}
});

Method 3: @RestController annotation (in this class So the method return values ​​are all Json)

Front end:

data:JSON.stringify({'channelId':channelId}),
                  success:function(data){
                        alert(data.channelId);
                  },
 
contentType:'application/json;charset=utf-8'

Backend:

@RequestMapping(value="/login",produces="application/json;charset=UTF-8") @ResponseBody public String test2() {  }

The above is the detailed content of How to return json in java. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn