如何使用继承设计具有通用零件的不同结构

时间:2018-06-21 14:27:31

标签: c# json design-patterns

我已经搜索了很多有关此问题的信息,但没有找到任何可观的结果(也许是因为我不清楚要问什么),那么我们在这里... 我必须设计从两个不同的JSON派生的两个结构,它们具有共同的组成部分:

{
  "data": 
    {
      "success": true,
      "updated_ids": [0],
      "not_updated_ids": [0]
    }
}

{
  "data": 
    {
      "success": true,
      "branch_ids":["0"]
    }
}

我的想法是创建这样的东西:

class Response
{
    Data data { get; set; }
}

class Data
{
    bool success { get; set; }
}

class UserResponse : Data
{
    List<int> updatedIds { get; set; }
    List<int> notUpdatedIds { get; set; }
}

class BranchResponse : Data
{
    List<string> branchIds { get; set; }
}

现在我的问题是:如何实例化两个不同的类? 如果我做new Response(),我不会得到UserReponseBranchResponse部分;如果我做new UserResponse(),我就不会得到Response部分。

基本上,我想为每个结构实例化一个变量,用所有值填充它,然后序列化以创建Json。

谢谢!

2 个答案:

答案 0 :(得分:3)

好的,所以您需要一个接口和一个工厂来完成您要在此处创建的内容。

public interface IData
{
    bool Success { get; set; }
}
public class Response
{
    public IData Data { get; set; }
}

public class UserData : IData
{
    public bool Success { get; set; }
    public List<int> UpdatedIds { get; set; }
    public List<int> NotUpdatedIds { get; set; }
}

public class BranchData : IData
{
    public bool Success { get; set; }
    public List<string> BranchIds { get; set; }
}

public class HowToUseIt
{

    public Response CreateResponse()
    {
        Response myReponse = new Response
        {
            Data = new UserData
            {
                Success = true,
                UpdatedIds = new List<int>(),
                NotUpdatedIds = new List<int>()
            }
        };

        return myReponse;
    }

    public void WhatKindOfDataDoIHave(Response response)
    {
        if (typeof(UserData) == response.Data.GetType())
        {
            //You have user data
        }
        else if (typeof(BranchData) == response.Data.GetType())
        {
            //You have branch data
        }
        else
        {
            //You have a problem!
        }
    }

}

答案 1 :(得分:1)

使用安德鲁的部分建议,我终于找到了一种对我有用的解决方案。将其发布给可能对此疯狂的任何人:

 let vm = this;
    axios.get("https...")
    .then(
      function(response) {

        if (response.status == 200) {
          vm.code = response.data.code;
          vm.eventDetails = {
            name: response.data.name,
            start_time: response.data.start_time,
            end_time: response.data.end_time,

            ticket_details: null
          };
        }
      },

      axios
        .get(
          "...")
        .then(function(response) {

          if (response.status == 200) {       
            vm.eventDetails.ticket_details = [];
            for (let i = 0; i < response.data.length; i++) {
     vm.eventDetails.ticket_details.push(response.data[i]);


              );
            }
          }
        })
    );