簡體   English   中英

Java class 實現 JSON 使用 Z7930C951E609E461E85226004ED1 序列化

[英]Java class implementation for JSON serialized using Jackson

I'm attempting to implement a part of the Microsoft Teams API within a Java application, and I'm looking for some advice on proper Java class structure and architecture when using the Jackson library to serialize Java objects to JSON. 目標是在某些階段完成后向 Teams 頻道發送消息。

我有一個測試 class 序列化為我想要的確切 JSON ,但基於我見過的其他實現,下面的代碼感覺它的結構不正確且不靈活。

我希望得到的 JSON 結構如下:

{
  "@context": "http://schema.org/extensions",
  "@type": "MessageCard",
  "correlationId": "104443c6-7acc-11ea-bc55-0242ac130003",
  "summary": "test.complete",
  "themeColor": "0076D7",
  "sections": [
    {
      "activityTitle": "Test Notification"
    },
    {
      "title": "Execution Status",
      "facts": [
        {
          "name": "Build Number",
          "value": "1"
        },
        {
          "name": "Description",
          "value": "Test Pipeline Description"
        },
        {
          "name": "Execution Name",
          "value": "Test Pipeline Name"
        },
        {
          "name": "Stage Name",
          "Value": "Deploy"
        },
        {
          "name": "Status",
          "value": "complete"
        },
        {
          "name": "Summary",
          "value": "pipeline has completed successfully"
        }
      ]
    }
  ],
  "potentialAction": [
    {
      "@context": "http://schema.org",
      "@type": "ViewAction",
      "name": "View Execution",
      "target": [
        "https://testdomain.com"
      ]
    }
  ]
}

我的測試 Java class 如下:

import java.util.*;
import com.fasterxml.jackson.annotation.*;

public class JacksonSerializerTest {
  private static String ACTIVITY_TITLE = "Test Notifications";
  private static String FACTS_TITLE = "Execution Status";

  @JsonProperty("@context")
  public String context = "http://schema.org/extensions";

  @JsonProperty("@type")
  public String type = "MessageCard";

  public String correlationId;
  public String summary;
  public String themeColor;

  private transient HashMap<String, Object> metadata;

  public JacksonSerializerTest(HashMap<String, Object> metadata) {
    this.correlationId = this.createRandomUUID();
    this.summary = "test.complete";
    this.themeColor = "0076D7";

    this.metadata = metadata;
  }

  public List<HashMap> getSections() {
    List<HashMap> sections = new ArrayList<>();
    HashMap<String, Object> activityTitle = this.getSection("activityTitle", ACTIVITY_TITLE);

    sections.add(activityTitle);
    sections.add((HashMap)this.getFacts());

    return sections;
  }

  public HashMap<String, Object> getSection(String name, Object obj) {
    HashMap<String, Object> section = new HashMap<>();

    section.put(name, obj);

    return section;
  }

  private HashMap<String, Object> getFacts() {
    HashMap<String, Object> facts = new HashMap<>();
    List<HashMap> factsList = new ArrayList<>();

    factsList.add((HashMap)this.getFact("Build Number", (String)metadata.get("buildNumber")));
    factsList.add((HashMap)this.getFact("Description", (String)metadata.get("description")));
    factsList.add((HashMap)this.getFact("Execution Name", (String)metadata.get("executionName")));
    factsList.add((HashMap)this.getFact("Stage Name", (String)metadata.get("eventName")));
    factsList.add((HashMap)this.getFact("Status", (String)metadata.get("executionStatus")));
    factsList.add((HashMap)this.getFact("Summary", (String)metadata.get("executionSummary")));

    facts.put("title", FACTS_TITLE);
    facts.put("facts", factsList);

    return facts;
  }

  public HashMap<String, String> getFact(String name, String value) {
    HashMap<String, String> fact = new HashMap<>();

    fact.put("name", name);
    fact.put("value", value);

    return fact;
  }

  public List<HashMap> getPotentialAction() {
    List<HashMap> potentialAction = new ArrayList<>();
    HashMap<String, Object> action = new HashMap<>();
    ArrayList<String> targets = new ArrayList<>();

    targets.add((String)metadata.get("executionUrl"));

    action.put("@context", "http://schema.org");
    action.put("@type", "ViewAction");
    action.put("name", "View Execution");
    action.put("target", targets);

    potentialAction.add(action);

    return potentialAction;
  }

  private static String createRandomUUID() {
    return UUID.randomUUID().toString();
  }
}

根據我一直在閱讀的內容,看起來我應該對部分和潛在操作元素使用嵌套類,但我一直在努力解決如何將嵌套類實現到 output 一個包含這些 arrays 中不同哈希值的數組。

截至目前,我並不打算實現整個 API,而是希望獲得一個特定的消息卡結構,如上面的 JSON 所示。 不過,我們可能希望在以后添加其他功能或使用不同的消息類型。

How can this class be improved and how should this Java object be structured to be more flexible if we do need to add additional elements based on the Teams API?

您可以從為 PotentialAction 和 Sections 創建單獨的類開始。 這是為了確保關注點分離。 就像是:

class PotentialAction { 
  private List<HashMap> potentialAction;
  //all business logic to generate Potential Action goes in this class
}

class Sections {
 private List<HashMap> sections;
 //all business logic to generate Sections goes in this class
}

然后,您創建一個抽象 class 與每個 api 具有的最低要求(如元數據)

abstract class APICommon {
 //compulsory attributes required by all api's
 private String accessToken;
}

現在定義 API 特定類來擴展抽象 class

class API1 extends APICommon {
 // all the api specific attributes
  public String correlationId;
  public String summary;
  public String themeColor;
  private PotentialAction potentialAction;
  private Sections sections;
}

優點:

  1. 通過將潛在的動作和部分分成不同的類,用於制作 JSON 的不同部分的業務邏輯現在被分離,這不僅使代碼干凈,而且可以為不同的 api 重用。

  2. 如果您有其他要求並且需要支持新的 api,您只需從我們的抽象 class APICommon 擴展另一個 class。 這確保了早期的實現不受影響,並使您的設計具有可擴展性。

希望這可以幫助:)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM