2016-10-07 8 views
3

返されたJSON配列をRESTful GETリクエストからC#の古いオブジェクトモデルに正常にデシリアライズします。json.netを使用してJSONを逆シリアル化し、配列インデックスをモデルプロパティとして抽出したい

私は[JSONProperty foo]アノテーションを使用してJSON名をモデルプロパティにバインドしています。 JSONが返さ

は次のようになります。

[{ 
    "ProductCode": "0129923083091", 
    "Description": "DIESEL ", 
    "SalesLitres": 6058.7347, 
    "SalesValue": 6416.2000 
}, 
{ 
    "ProductCode": "0134039344902", 
    "Description": "UNLEADED ", 
    "SalesLitres": 3489.8111, 
    "SalesValue": 3695.7100 
}, 
... 
] 

私はJSONから返された配列項目の出現順序に基づいて合成された私のモデル内で一意のインデックスフィールドに似て何かを作成したいです。参考のため

、私の現在の注釈(インデックスプロパティなし)ので、次のようになります。

namespace App8.Models 
{ 
    public class ReportRow 
    { 
     [JsonProperty("ProductCode")] 
     public string ProductCode { get; set; } = string.Empty; 

     [JsonProperty("Description")] 
     public string Description { get; set; } = string.Empty; 

     [JsonProperty("SalesLitres")] 
     public double SalesLitres { get; set; } = 0.0; 

     [JsonProperty("SalesValue")] 
     public double SalesValue { get; set; } = 0.0;  
    } 
} 

はNewtonsoft JSON.netによって提供されるこのための注釈が... そこであるか、そのいくつかのコードがあります私はゲッター/セッターの中に主キーを製造することができます。

答えて

1

データ

var data = JsonConvert.DeserializeObject<List<ReportRow>>(json); 

あなたは、インデックスを取得するためにLINQを選択し使用することができますをデシリアライズした後

public class ReportRow { 
    public int Index { get; set; } 

    [JsonProperty("ProductCode")] 
    public string ProductCode { get; set; } = string.Empty; 

    [JsonProperty("Description")] 
    public string Description { get; set; } = string.Empty; 

    [JsonProperty("SalesLitres")] 
    public double SalesLitres { get; set; } = 0.0; 

    [JsonProperty("SalesValue")] 
    public double SalesValue { get; set; } = 0.0;  
} 

を仮定。

var indexedData = data.Select((item, index) => { 
    item.Index = index; 
    return item; 
}).ToList(); 

または、インデックスがモデル上のプロパティでない場合は、タイプをオンザフライで作成します。

var indexedData = data.Select((item, index) => new { 
    Index = index, 
    ReportRow = item 
}).ToList(); 
+0

非常によく見えます。私は確かにそれを試してみましょう。 – retail3r

+0

linqを使って副作用を引き起こすのはちょっと怪しいです。クエリを列挙しない場合、副作用は決して実行されません! –

関連する問題