簡體   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