如何使用$符号获取Json变量 [英] How to get Json variable with $ symbol
本文介绍了如何使用$符号获取Json变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我一直在努力获取$type
变量.
I've been pulling my hair to get the $type
variable.
jsonTxt.json
jsonTxt.json
{
"$type": "Things.YourThings.YourThingName, Things",
"Name": "Doe"
}
我试图将变量作为string
获得,但没有成功.我刚得到null
.
I tried to get the variable as a string
, but with no success. I just get null
.
这是我的工作:
public class CustomName
{
[JsonProperty("$type")]
public string Type { get; set; }
public string Name { get; set; }
}
然后
var customName = JsonConvert.DeserializeObject<CustomName>(jsonText);
实际上,我只想提取名称为YourThingName
的类型.
In actual fact, I just want to extract the type which is just the name YourThingName
.
推荐答案
尝试一下:
JObject obj = JObject.Parse(jsonText);
var customName = new CustomName()
{
Name = obj["Name"].ToString(),
Type = obj["$type"].ToString()
};
然后只得到YourThingName
即可使用正则表达式或仅使用String.Split
:
Then to get just the YourThingName
you can either use a Regex or just String.Split
:
string name = Regex.Match(customName.Type, @"(?:\.)(\w*)(?:,)").Groups[1].ToString();
或
string name = customName.Type.Split(',')[0].Split('.')[2];
您必须先进行边界检查,然后才能访问不同的数组,否则将出现IndexOutOfRange
异常.
You must do your boundary checks before accessing the different arrays or you'll end up with IndexOutOfRange
exceptions.
这篇关于如何使用$符号获取Json变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文