使用Decodable解码具有不同JSON的模型

情境 (Scenario)

I know this is not everyday scenario that we face but there can be many situation where you may have implement this kind of behavior instead of duplicating same contextual models with weird names and have redundant code. Example

我知道这不是我们每天都会遇到的情况,但是在许多情况下,您可能已经实现了这种行为,而不是使用怪异的名称复制相同的上下文模型并使用了多余的代码。

  • An App accessing user data from two different sources with different JSON object even though the user is same in those different sources. Example: A super app providing services from different services provided user is having account on those services

    一个App从具有不同JSON对象的两个不同来源访问用户数据,即使这些不同来源中的用户相同。 示例 :提供来自不同服务的服务的超级应用程序(如果用户拥有这些服务)

In scenario like this you will be working with different API endpoint of these services and parse the JSON.

在这种情况下,您将使用这些服务的不同API终结点并解析JSON。

So the question is how will achieve this with Decodable?

那么问题是如何用Decodable实现呢?

让我们开始解码 (Let’s Start Decoding)

In the below example gist, I have added two scenarios of user JSON we will receive in our app from different scenarios. Now what we did is

在下面的示例要点中,我添加了两种用户JSON场景,我们将从不同的场景中接收到我们的应用程序。 现在我们要做的是

  • We created a user object which implements Decodable with keys we need to parse in it.

    我们创建了一个用户对象,该对象使用需要解析的键来实现Decodable

  • We created two different CodingKeys for our case as we are expecting two different sources, In this case ServiceOneCodingKeys and ServiceTwoCodingKeys which handle the user object for this two different services.

    我们为我们的案例创建了两个不同的CodingKeys ,因为我们期望有两个不同的来源,在这种情况下, ServiceOneCodingKeysServiceTwoCodingKeys可以处理这两个不同服务的用户对象。

  • Now comes the Important part where we implement custom init(from decoder: Decoder) , In this we implement custom strategy to decode our user object with two different JSON, The implementation is straight forward as you can see we first decode it first with ServiceOne container and verify any variable in this case userId and if we found it nil we move towards to second container.

    现在是重要部分,我们在其中实现了自定义init(from decoder: Decoder) ,在此我们实现了自定义策略,以使用两个不同的JSON解码用户对象,实现非常简单,因为您可以看到我们首先使用ServiceOne容器对其进行了解码并验证在这种情况下,任何变量userId ,如果我们发现它nil我们朝着第二容器移动。

  • Lastly if none of container works we send fatalError in this case, We can also send crash report to verify the unknown issues.

    最后,如果在这种情况下没有容器可以正常工作,我们将发送fatalError ,我们也可以发送崩溃报告以验证未知问题。

感谢您的阅读 (Thank you for reading)

I hope this article helps you, You can copy the gist in Xcode playground and have a hands on with your custom scenarios.

希望本文对您有所帮助,您可以在Xcode操场上复制要点,并尝试使用自定义方案。

翻译自: https://medium.com/flawless-app-stories/decoding-a-model-with-different-json-with-decodable-c4cc6f502551

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值