Serializing JSON from SpecFlow table

1.2k Views Asked by At

I have question which is related with JSON serialization from specflow table. I have the following step in spec flow feature file:

When user initiates transaction with data:

|  Key          |  Value              |
| --------------|---------------------| 
|Merchant       |  TestMerchant       |
|Shop           |  TestShop           |
|Currency       |  USD                |
|Amount         |  10.00              |
|User.ID        |  Test_User_01       |
|User.FirstName |  Test_User_FirstName|
|User.LastName  |  Test_User_LastName |

I have two models, which look like follows:

 class User
    {
      public string ID {get; set;}
      public string FirstName {get; set;}
      public string LastName {get; set;}   
    }

 class TransactionReq
    {
      public string Merchant {get; set;}
      public string Shop {get; set;}  
      public string Currency {get; set;}  
      public decimal Amount {get; set;}  
      public User User {get; set;} //<--
    }

[When(@"user initiates transaction with data:")]

public void UserInitiatesTransaction(Table table)
{
    var transactionData = table.CreateInstance<TransactionReq>();
    //this is part of the code in the step
}

In the step definition I'm using assist helper method to get data from the table, apparently the assist helper is not felt and does not map user data. I want to serialize data to JSON to look like the example below.

 {
       "Merchant":"TestMerchant",
       "Shop":"TestShop",
       "Amount":10.00,
       "Currency":"EUR",
       "User":{
          "Id":"Test_User_01",
          "FirstName":"Test_User_FirstName",
          "LastName":"Test_User_LastName",
       }
    }

Can you give me advice for approach, is Newtonsoft contains resources for serialization to json from table or dictionary with such structure of table like the one I described above?

1

There are 1 best solutions below

1
Serge On

you can try this code

using Newtonsoft.Json;

var transactionData = table.CreateInstance<TransactionReq>();

var json = JsonConvert.SerializeObject(transactionData);

it was tested in Visual Studio, this is a result

{
  "Merchant": "TestMerchant",
  "Shop": "TestShop",
  "Currency": "USD",
  "Amount": 10.00,
  "User": {
    "ID": "Test_User_01",
    "FirstName": "Test_User_FirstName",
    "LastName": "Test_User_LastName"
  }
}