我有一个ASP.NET Core MVC应用程序的输入请求正文,该应用程序绑定到C#中的请求模型。
public class Request
{
public int Index {get;set;}
public string DocType {get;set;}
public string DocId {get;set;}
}
这是我的请求JSON
{
"request" : [
{
"DocType" : "MSWORD",
"DocId" : "553ed6c232da426681b7c45c65131d33"
},
{
"DocType" : "MSEXCEL",
"DocId" : "256ed6c232da426681b7c45c651317895"
}]
}
我想将此请求映射到我的C#模型,以使Index
属性自动增加。
换句话说,当我将C#请求反序列化为JSON字符串时,它应该看起来像这样。
{
"request" : [
{
"Index" : 0,
"DocType" : "MSWORD",
"DocId" : "553ed6c232da426681b7c45c65131d33"
},
{
"Index" : 1,
"DocType" : "MSEXCEL",
"DocId" : "256ed6c232da426681b7c45c651317895"
}]
}
答案 0 :(得分:1)
在序列化为JSON之前,只需使用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();
更新 感谢Erik和他的注释,上面的代码可以简化为
var newList = list.Select((x, index) =>
{
x.Index = index;
return x;
}).ToList();
答案 1 :(得分:-1)
声明一个静态int变量以保存数字,并使用构造函数将值分配给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; }
}
}