我有一个 .NET Core 1.x Web API 项目,我试图在 HTTP post 上接受一个数组,但我一直无法让它工作。我已经验证了以下 JSON
{
"LogEntry": [{
"a": 1238976,
"b": "test",
"c": "sub test",
"d": "some syb system comp",
"e": 1234,
"f": "my category",
"g": "my event name",
"h": "my sub event",
"i": "user def 1",
"j": "7/22/2008 12:11:04 PM",
"k": 45,
"l": 65,
"n": "Chris",
"o": "C:\\temp\\",
"p": 1234567890,
"q": 84,
"r": "eeeee stuff",
"s": "ddddd stuff",
"t": 90210
}]
}
我有一个模型类,所以我需要将每个数组项添加到模型类型的列表中。这就是我被困的地方。我只能使用不在数组中的单个条目来实现它。我针对该场景的 C# 是:
[HttpPost]
public string Post([FromBody] JObject test)
{
var result = JsonConvert.DeserializeObject<EventManagerLogEntry>(test.ToString());
return "wootwoot";
}
关于如何遍历我的 jObject 中的每个数组并将其添加到类型列表的任何方向都将非常有帮助。
类定义
public class EventManagerLogEntry
{
public int a { get; set; }
public string b { get; set; }
public string c { get; set; }
public string d { get; set; }
public int e { get; set; }
public string f { get; set; }
public string g { get; set; }
public string h { get; set; }
public string i { get; set; }
public string j { get; set; }
public int k { get; set; }
public int l { get; set; }
public string m { get; set; }
public string n { get; set; }
public int o { get; set; }
public int p { get; set; }
public string q { get; set; }
public string r { get; set; }
public int s { get; set; }
}
更新 我尝试了几种不同的方法,这似乎对我有用。
[HttpPost]
public HttpResponseMessage Post([FromBody] JArray test)
{
var list = JsonConvert.DeserializeObject<List<EventManagerLogEntry>>(test.ToString());
foreach (EventManagerLogEntry x in list)
{
//_context.EventManagerLogEntry.Attach(x);
//_context.SaveChanges();
}
return new HttpResponseMessage(System.Net.HttpStatusCode.OK);
}
最佳答案
使用这个模型反序列化你的json
public class Log
{
public List<Dictionary<string,string>> LogEntry { get; set; }
}
var log = JsonConvert.DeserializeObject<Log>(json);
你也可以使用linq
var jObj = JObject.Parse(json);
var listOfDict = jObj["LogEntry"]
.Select(x => x.Cast<JProperty>()
.ToDictionary(p => p.Name, p => p.Value))
.ToList();
关于c# - RESTful 服务和 JSON 数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46202756/