2017-05-01 7 views
-6

次のJSONをnewtonsoft.netを使用して解析する必要があります。私は多くのコードを試しましたが、彼らは働いていません。json.netを使用してJSONを解析するC#

{ 
    "tableId": 1, 
    "userId": 12, 
    "branchId": 2, 
    "cart": [{ 
     "itemId": 12, 
     "itemname": "Paneer butter masala", 
     "qty": "1", 
     "price": "2500", 
     "customise": [{ 
      "name": "fruit boul", 
      "id": 1, 
      "price": "25" 
     }, { 
      "name": "fruit boul", 
      "id": 1, 
      "price": "25" 
     }], 
     "comment": "", 
     "linetotal": "2550" 
    }, { 
     "itemId": 34, 
     "itemname": "Paneer butter masala", 
     "qty": "1", 
     "price": "2500", 
     "customise": [{}], 
     "comment": "", 
     "linetotal": "2500" 
    }], 
    "total": "5050" 
} 

いずれの回答も高く評価されます。 (あなたが好きな場合は旧来のC#クラス)

+5

としてJSONとして貼り付けます。*あなたは何を試してみましたか?そして、それらの "コード"とは*働いていないものは何ですか?あなたの最も有望な試みを含めて、働いていないものを教えてください。それはコンパイルされませんか?実行時にエラーが出るのですか?それは実行されますが、あなた以外の何かが期待していますか?とにかくこれを解析したいのですか? –

+0

私はJObject.Parse()、JToken、JArrayなどで試しました。カート内の各項目、配列をカスタマイズする項目が必要です –

+2

あなたの投稿にC#コードを含めることを**表示**する必要があります。今のところ、あなたが何を求めているのかは不明です。 –

答えて

1

ステップ1.(http://json2csharp.com/によって生成される)にあなたのJSONをデシリアライズするためにいくつかのモデルを作る - これは、一般的にそのまっすぐJSONで動作するように少し簡単です:

public class Customise 
{ 
    public string name { get; set; } 
    public int id { get; set; } 
    public string price { get; set; } 
} 

public class Cart 
{ 
    public int itemId { get; set; } 
    public string itemname { get; set; } 
    public string qty { get; set; } 
    public string price { get; set; } 
    public List<Customise> customise { get; set; } 
    public string comment { get; set; } 
    public string linetotal { get; set; } 
} 

public class TableData 
{ 
    public int tableId { get; set; } 
    public int userId { get; set; } 
    public int branchId { get; set; } 
    public List<Cart> cart { get; set; } 
    public string total { get; set; } 
} 

ステップ2:私はこれができ、あなたのルートオブジェクトTableDataの名前(設定されたすべての値を持つオブジェクトのインスタンスを取得するなど、あなたのJSON文字列をデシリアライズNuGetパッケージマネージャを経由して、プロジェクトに

ステップ3をJson.NETの依存関係を追加します。明らかに変更される):

var data = JsonConvert.DeserializeObject<TableData>(jsonString); 

すべてのjsonデータは、dataオブジェクト内で設定されています。あなたがここにNewtonsoft.Json.JsonConvert.DeserializeObjectを使用する必要があります

+0

ありがとうnbokmans。それは期待どおりに働いています –

0

はどのように自動的にJSONデータを有する適切なクラスを作成するためのサンプル

var jsonFilePath = path to your file; 

var myObject = Newtonsoft.Json.JsonConvert.DeserializeObject(System.IO.File.ReadAllText(jsonFile)); 

のですか?

手動であなたのJSONデータを使用して、適切なクラスを作成したくない場合は、すべてのあなたのJSONテキストを選択することができますし、Visual Studioで次の手順を実行します。

編集>貼り付けを>私は多くのコードを試みたが、彼らは働いていない*クラス

enter image description here

関連する問題