3
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

Json形式のファイルをApexで処理する

Last updated at Posted at 2022-03-05

個人的にはClassを定義して一発で変換する方法が好きですが、1つずつ変換する方法での質問に答えました。

このファイルを変換します。

{
    "d": {
        "results": [
            {
                "__metadata": {                    
                    "uri": "https://itsm-webservice.com:5000/CMDS/GetMaterial?id=80016757&Srnum=26090"
                },
                "ItemNumber": "0003",
                "Sernr": "359117093739281G",
                "Batch": "7500038949",
                "Documentyear": "2019",
                "Qty": "1.000",
                "Ittagno": "359117093739281",
                "Pempno": "84236527"
            }
        ]
    }
}

質問者さんのコード

Map<String, Object> mapResponseData = (Map<String, Object>)Json.deserializeUntyped(res.getBody());
Map<String, Object> dataToBePassed = (Map<String, Object>)mapResponseData.get('d');
system.debug('dataToBePassed::'+dataToBePassed);
String Sernr = String.valueOf(dataToBePassed.get('Sernr'));
String Batch = String.valueOf(dataToBePassed.get('Batch'));
String Ittagno = String.valueOf(dataToBePassed.get('Ittagno'));
system.debug('Sernr::'+Sernr);
system.debug('Batch::'+Batch);
system.debug('Ittagno::'+Ittagno);

image.png

Sernr、Batch、Ittagnoに値がないようです。
よくJsonのデータを見ると、resultsの構成を変換してないように思います。まずはresultsを読みましょう。

私のコードは以下です。

Map<String, Object> mapResponseData = (Map<String, Object>)Json.deserializeUntyped(res.getBody());
system.debug('mapResponseData::' + mapResponseData);
       
Map<String, Object> dataToBePassed = (Map<String, Object>)mapResponseData.get('d');        
system.debug('dataToBePassed::'+dataToBePassed);
        
List<Object> dataToResults = (List<Object>)dataToBePassed.get('results');  
system.debug('dataToResults::'+dataToResults);
        
String Sernr = (String)((Map<String, Object>)dataToResults[0]).get('Sernr');
system.debug('Sernr::'+Sernr);
String Batch = (String)((Map<String, Object>)dataToResults[0]).get('Batch');
system.debug('Batch::'+Batch);
String Ittagno = (String)((Map<String, Object>)dataToResults[0]).get('Ittagno');  
system.debug('Ittagno::'+Ittagno);

ポイントはresultsは各フィールドが存在するList型の変数になるということです。
また、そのList変数の各値を読むためには無理やり(Map)にキャストします。
これで読めます。

image.png

Salesforce external Web Service Issue

3
1
0

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
3
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?