简体   繁体   English

检查 JValue 是否为 C# 中的数组

[英]Check if the JValue is an Array in C#

I have a Json string我有一个 Json 字符串

string s =  @"{""A"": [""AB""]}"

I want to check if the JValue is an Array or not.我想检查JValue是否为数组。 My jsonstring can have an array or can also be我的 jsonstring 可以有一个数组,也可以是

string s =  @"{""A"": ""A[B""}"

The only way that i can find is JObject.Parse(s)["A"].Contains("[") .我能找到的唯一方法是JObject.Parse(s)["A"].Contains("[") But this is not always true as my string itself can have "[" or "]".但这并不总是正确的,因为我的字符串本身可以有“[”或“]”。 Please suggest a solution in C#请在 C# 中提出解决方案

Typically you would let the JSON parser deduce that for you.通常,您会让 JSON 解析器为您推断。 If you're using Newtonsoft, then it could look like this:如果您使用的是 Newtonsoft,那么它可能如下所示:

var str0 = @"{""A"": [""AB""]}";
var str1 = @"{""A"": ""A[B""}";
var o0 = JObject.Parse(str0);
var o1 = JObject.Parse(str1);
Console.WriteLine("o0.A type: " + o0["A"].Type);
Console.WriteLine("o1.A type: " + o1["A"].Type);

The output would be: output 将是:

o0.A type: Array
o1.A type: String

You can also use SelectToken method using jsonPath in Newtonsoft.您还可以使用 Newtonsoft 中的 jsonPath 使用 SelectToken 方法。 like this:像这样:

            string s1 = @"{""A"": [""AB""]}";
            string s2 = @"{""A"": ""A[B""}";
            var parseS1 = JToken.Parse(s1);
            var parseS2 = JToken.Parse(s2);
            Console.WriteLine(parseS1.SelectToken("A").Type);
            Console.WriteLine(parseS2.SelectToken("A").Type); 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM