Home > Java > javaTutorial > body text

How to return json in java

(*-*)浩
Release: 2020-09-16 17:33:04
Original
9758 people have browsed it

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()); 
}
Copy after login

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; 
}
}
});
Copy after login
Copy after login

Method 2: @ResponseBody Annotation

Backend:

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

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; 
}
}
});
Copy after login
Copy after login

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'
Copy after login

Backend:

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

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!

Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template