[英]Return just Keys from json HttpContext.Response in C#
I have a HttpContext.Response
function which returns this json response:我有一个HttpContext.Response
函数,它返回这个 json 响应:
{
"[2-1] STORE[STORE_NBR]": 5026,
"[2-1] STORE[STATE_PROV_CD]": "AR"
}
Now, I just want the Keys to be returned and not the value as:现在,我只想返回键而不是值:
{
[2-1] STORE[STORE_NBR],
[2-1] STORE[STATE_PROV_CD]
}
I tried commenting [1] and [2] but that result in an exception as value is expected.我尝试评论 [1] 和 [2] 但这会导致异常,因为值是预期的。 How can this outcome be achieved?怎样才能达到这个结果?
The Json response (as noted in a comment) can be easily deserialized to a Dictionary where both the Key
and the Value
of the KeyValuePair
are strings. Json 响应(如评论中所述)可以轻松反序列化为字典,其中KeyValuePair
的Key
和Value
都是字符串。 Here is how you could do that:您可以这样做:
using System.Linq;
using Newtonsoft.Json; // Can be installed as a NuGet package
then然后
var dictionary =
JsonConvert.DeserializeObject<Dictionary<string,string>>(source);
Once you have the dictionary object, you can use Linq to extract just the Keys that you want and turn them into a list.一旦你有了字典对象,你就可以使用 Linq 只提取你想要的键并将它们变成一个列表。
List<string> keys =
dictionary.Select(keyValuePair => keyValuePair.Key).ToList();
where在哪里
const string source =
@"{
""[2 - 1] STORE[STORE_NBR]"": 5026,
""[2-1] STORE[STATE_PROV_CD]"": ""AR""
}";
These lines of code format the output you specified:这些代码行格式化您指定的输出:
Console.WriteLine(
"Here are the keys:");
Console.WriteLine(
$"{{{Environment.NewLine}{string.Join("," + Environment.NewLine, keys)}{Environment.NewLine}}}");
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.