繁体   English   中英

"如何从服务器端对象调用 javascript 对象的属性\/方法"

[英]How to call properties/methods of a javascript object from server side object

我通常使用 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 做同样的事情。所以我的班级 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 中开发人员工具的输出。

在此处输入图像描述

在您的情况下,Java对象正在被序列化为JSON,以通过电线发送到浏览器,但是fullName字段并未与该对象一起序列化。 尽管javascript无法访问方法getFullName,但是您可以序列化任意字段,例如在Java端包括fullName字段。 我无法告诉您正在使用Jersey的序列化库,但是如果使用的是Jackson,则可以简单地将方法注释为JSON属性:

@JsonProperty("fullName")   
public string getFullName() {
    return this.firstName + " " + this.lastName;   
}

您还可以使用Moesif和Fiddler之类的工具来查看通过导线的有效载荷是多少。

在 c# 中,您的 GetFullName 是一个属性。 在 Java 中,它是一个函数。

JSON 仅序列化属性。 如果您希望您的 Java 对象序列化 FullName,您必须将其转换为属性或对其进行注释。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM