我对此并不陌生,如果是重复的问题,我深表歉意。在这一点上,我已经尝试了很多不同的方法,但我不确定这样做的正确方法。
我正在尝试编写一个函数来遍历JSON
并获取特定条件(例如:qty != null
和sector = 1
,position = 1
)的模型值。
我还需要计算每个唯一模型的出现次数。 任何帮助将不胜感激。
JSON
的外观如下。
[ { "sector": "1", "position": "1", "qty": "1", "model": "SBNHH-1D65C" },
{ "sector": "2", "position": "1", "qty": "1", "model": "" },
{ "sector": "3", "position": "1", "qty": "1", "model": "DC6-48-60-18-8F" },
{ "sector": "1", "position": "2", "qty": "1", "model": "SBNHH-1D65C" },
{ "sector": "2", "position": "2", "qty": "1", "model": "DC6-48-60-18-8F" } ]
public class AntennaItems
{
public AntennaItems[] root { get; set; }
public int sector { get; set; }
public int position { get; set; }
public string qty { get; set; }
public string model { get; set; }
}
string requestBodyString = await new StreamReader(req.Body).ReadToEndAsync();
var newJsonString = @"{root:" + requestBodyString + @"}";
List<string> modelList = new List<string>();
var jsonObj = JsonConvert.DeserializeObject<AntennaItems>(newJsonString);
foreach (var elem in jsonObj.root)
{
modelList.Add(elem.model);
}
return new OkObjectResult($"modelList = {modelList}");
目前,我收到以下答复:
modelList = System.Collections.Generic.List`1[System.String]
答案 0 :(得分:0)
我认为您不需要root属性。我对类做了一些修改,并从其中删除了root属性:
ID Mobile Pref Email Pref
1 1234567890 A test@test.com A
2 1234567891 A test@test.com B
您需要在列表中反序列化它。让我知道是否有帮助。
答案 1 :(得分:0)
public class AntennaItems
{
public int sector { get; set; }
public int position { get; set; }
public string qty { get; set; }
public string model { get; set; }
[FunctionName("AntennaSort")]
public static async Task<IActionResult> Run(
[HttpTrigger(AuthorizationLevel.Function, "get", "post", Route = null)] HttpRequest req,
ILogger log)
{
log.LogInformation("C# HTTP trigger function processed a request.");
string requestBody = await new StreamReader(req.Body).ReadToEndAsync();
List<string> modelList = new List<string>();
var jsonObj = JsonConvert.DeserializeObject<List<AntennaItems>>(requestBody);
foreach (var elem in jsonObj)
{
modelList.Add(elem.model);
}
return new OkObjectResult($"modelList = {modelList}");
}
结果是 modelList = System.Collections.Generic.List`1 [System.String]
答案 2 :(得分:0)
您将以字符串名称modelList
进行插值,返回modelList
,插值将返回modelList
的类型,在您的情况下为System.Collections.Generic.List'1[System.String]
。
所以这行
return new OkObjectResult($"modelList = {modelList}");
给你
modelList = System.Collections.Generic.List`1[System.String]
因此,与其像上面那样返回,请尝试使用匿名类型返回您的modelList
,这样您就可以获取包含modelList
的实际数据,例如
return new OkObjectResult(new { modelList = modelList});
或者简单地
return new OkObjectResult(modelList);