【发布时间】:2017-02-25 21:32:27
【问题描述】:
我通常使用 C#、jQuery 2.x、Chrome 作为这样的浏览器从 restful 资源 Web Api 2 获取 js 对象
C#
public class Employee
{
private int id;
private string firstName;
private string lastName;
public int ID
{
get{ return this.id; }
set{ this.id = value; }
}
public string FirstName
{
get{ return this.firstName; }
set{ this.firstName = value; }
}
public string LastName
{
get{ return this.lastName; }
set{ this.lastName = value; }
}
public string FullName
{
get{ return this.firstName + " " + this.lastName; }
}
}
我有一个这样的控制器
public class EmployeeController : ApiController
{
[HttpGet]
public Employee GetEmployee(int id)
{
return EmployeeService.Instance.GetEmployee(id);
}
}
然后在我的js中我这样调用资源
function getEmployee(id) {
$.ajax({
type: "GET",
url: "localhost:8080/Employee/" + id,
success: bindEmployee
});
}
function bindEmployee(employee){
alert(employee.FullName);
}
Java
现在我想使用 Jersey 2.23、Java json 1.0、Tomcat 8 在 Java 中做同样的事情。所以我的班级 Employee
public class Employee{
private int ID;
private string firstName;
private string lastName;
//regular getter and setter methods
public string getFullName(){
return this.firstName + " " + this.lastName;
}
}
这是我宁静的资源
@Path("/employee")
public class EmployeeController {
@GET
@Produces(MediaType.APPLICATION_JSON)
public Response getEmployee(@PathParam("id") long id) throws JSONException{
Employee employee = new Employee();
employee.setId(id);
employee.setFirstName("john");
employee.setLastName("smith");
return Response.status(200).entity(employee).build();
}
}
我像这样用 angularjs 中的 $http 对象调用 restful 资源
return $http({
method : 'GET',
url : 'localhost:8080/employee/1',
}).then(onSuccess, onError);
function onSuccess(response){
return response.data;
}
function onError(response){
//
}
响应数据是我的员工,但我只能看到私有成员,但我无法调用 getFullName 方法。不在 JSON 字符串中,它是一个 Javascript 对象。
是否有在 javascript 中调用 getFullName 的解决方法?我想避免像这样 firstName + " "+ lastName 这样的客户端连接。
这是 Chrome 中开发者工具的输出。
【问题讨论】:
-
问题很不清楚。在哪里使用什么语言(客户端/服务器/浏览器)?无论语言如何,实际传输的 JSON 数据是否总是相同的,它是什么样的?
-
我更新了我的问题。
-
顺便说一句,为什么要关闭投票。用户可以好心解释一下原因吗?
-
您是否阅读了Jersey document about JSON,其中指定了如何控制 POJO 映射到 JSON 的方式?它有您正在寻找的答案,就像大多数文档一样。
标签: javascript java c# jquery angularjs