LoginSignup
0
0

More than 3 years have passed since last update.

Apex Specialist Super Badge 復習[Challenge 2]

Last updated at Posted at 2019-09-16

WarehouseEquipmentクラス

responseされたJSONをデシリアライズするためのクラス。

public class WarehouseEquipment {
    public String name;
    public Boolean replacement;
    public Integer quantity;
    public Integer maintenanceperiod;
    public Integer lifespan;
    public Integer cost;
    public String sku;
    public String x_id;

    public List<WarehouseEquipment> parse(String json){
        json.replace( '"_id":', '"x_id":' );
        return (List<WarehouseEquipment>) System.JSON.deserialize(json,List<WarehouseEquipment>.class);
    }
}

System.JSON.deserializeメソッドについて

trailなどではSystem.JSON.deserializeUntyped(String json)が紹介されています。これはObjectが返されるので、Map<String,Object>にキャストすることで扱うことができるようになります。
私はSystem.JSON.deserialize(String json,apexType)を使いました。(上記コード)
戻り値は同じくObjectなので、型変換をする必要があります。キャストしたコレクションは、
作成したクラスの対応するフィールドに格納されます。型変換も行われるので下記コールアウトクラスが簡潔になるのがメリット。
もちろん、項目名の対応などが間違っているとエラーになります。

WarehouseCalloutServiceクラス

厳密には単純なupsertだと適切な動作をしない(全部insertになってしまう)がとりあえずその辺は保留。
正常なレスポンスが返ってきたらJSONを変換してupsert

コード
public with sharing class WarehouseCalloutService {
    private static final String WAREHOUSE_URL = 'https://th-superbadge-apex.herokuapp.com/equipment';
    // complete this method to make the callout (using @future) to the
    // REST endpoint and update equipment on hand.
    @future(callout=true)
    public static void runWarehouseEquipmentSync(){
        Http http=new Http();
        HttpRequest request=new HttpRequest();
        request.setEndpoint(WAREHOUSE_URL);
        request.setMethod('GET');
        request.setHeader( 'Content-Type', 'text-xml' );
        HttpResponse response=http.send(request);
        if(response.getStatusCode()==200){
            List<Product2> listp=new List<Product2>();
            for(WarehouseEquipment eq:new WarehouseEquipment().parse(response.getBody())){
                Product2 p=new Product2(Id=eq.x_id);
                p.Replacement_Part__c=true;
                p.Cost__c=eq.quantity;
                p.Lifespan_Months__c=eq.lifespan;
                p.Maintenance_Cycle__c=eq.maintenanceperiod;
                p.Name=eq.name;
                p.Warehouse_SKU__c=eq.sku;
                listp.add(p);
            }
            upsert listp;
        }
    }
}

Challenge2をクリアするには

Before checking this section, run the WarehouseCalloutService.runWarehouseEquipmentSync() method at least once

DebugタブのOpen Execute Annopnymous Windowから実行すればよいようです。

続き:Apex Specialist Super Badge 復習[Challenge 3]

0
0
2

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0