0

I have an input request body for my ASP.NET Core MVC application which I am binding to a request model in C#.

public class Request 
{
    public int Index {get;set;}
    public string DocType {get;set;}
    public string DocId {get;set;}
}

This is my request JSON

{
"request" : [
    {
        "DocType" : "MSWORD",
        "DocId"   : "553ed6c232da426681b7c45c65131d33"
    },
    {
        "DocType" : "MSEXCEL",
        "DocId"   : "256ed6c232da426681b7c45c651317895"
    }]
}

I want to map this request to my C# model such that the Index property is incremented automatically.

In other words, when I Deserialize my C# request to a JSON string it should look like this.

{
"request" : [
    {
        "Index"   : 0,
        "DocType" : "MSWORD",
        "DocId"   : "553ed6c232da426681b7c45c65131d33"
    },
    {
        "Index"   : 1,
        "DocType" : "MSEXCEL",
        "DocId"   : "256ed6c232da426681b7c45c651317895"
    }]
}
Code-47
  • 413
  • 5
  • 17

2 Answers2

1

Before serializing to JSON just do a simple "converstion" using LINQ:

//below should be your original list instead of this test data
var list = new List<Request>
{
    new Request {DocId = "000", DocType = "type"},
    new Request {DocId = "111", DocType = "type"},
    new Request {DocId = "222", DocType = "type"}
};

var count = 0;

var newList = list.Select(x =>
{
    x.Index = count++;
    return x;
}).ToList();

UPDATE Thanks to Erik and his comment above code can be simplified to

var newList = list.Select((x, index) =>
{
    x.Index = index;
    return x;
}).ToList();
Piotr Stapp
  • 19,392
  • 11
  • 68
  • 116
0

Declare a static int variable to hold the number and use the constructor to do assign the value to the Index.

using System.Collections.Generic;
using Newtonsoft.Json;

namespace ConsoleApp2 {
  class Program {
    static void Main() {

      string json = @"[{'DocType' : 'MSWORD','DocId'   : '553ed6c232da426681b7c45c65131d33'},{'DocType' : 'MSEXCEL','DocId'   : '256ed6c232da426681b7c45c651317895'}]";
      Request.Seed = 1;
      var r = JsonConvert.DeserializeObject<List<Request>>(json);
      Request.Seed = 100000;
      r = JsonConvert.DeserializeObject<List<Request>>( json );

    }
  }
  public class Request {
    public static int Seed { get; set; }

    public Request() {
      Index = Seed++;
    }
    public int Index { get; set; }
    public string DocType { get; set; }
    public string DocId { get; set; }
  }
}
Ihtsham Minhas
  • 1,415
  • 1
  • 19
  • 31