![](/img/trans.png)
[英]How to display value of the variable and symbol '$' in the one label?
[英]How to get Json variable with $ symbol
我一直在拉我的头发来获取$type
变量。
jsonTxt.json
{
"$type": "Things.YourThings.YourThingName, Things",
"Name": "Doe"
}
我试图将变量作为string
,但没有成功。 我得到null
。
这是我做的:
public class CustomName
{
[JsonProperty("$type")]
public string Type { get; set; }
public string Name { get; set; }
}
然后,
var customName = JsonConvert.DeserializeObject<CustomName>(jsonText);
实际上,我只想提取名称为YourThingName
的类型。
试试这个:
JObject obj = JObject.Parse(jsonText);
var customName = new CustomName()
{
Name = obj["Name"].ToString(),
Type = obj["$type"].ToString()
};
然后要获得YourThingName
您可以使用正则表达式或只使用String.Split
:
string name = Regex.Match(customName.Type, @"(?:\.)(\w*)(?:,)").Groups[1].ToString();
要么
string name = customName.Type.Split(',')[0].Split('.')[2];
您必须在访问不同的阵列之前进行边界检查,否则最终会导致IndexOutOfRange
异常。
另一个解决方案是用"$type"
的东西替换所有出现的"$type"
"type"
。
jsonText.Replace("\"$type\"", "\"type\"");
随着...
public class CustomName
{
public string Type { get; set; }
public string Name { get; set; }
}
...反序列化将按预期工作:
var customName = JsonConvert.DeserializeObject<CustomName>(jsonText);
var type = customName.Type;
Json.Net提供了MetadataPropertyHandling
设置,该设置控制它如何处理JSON中的$type
, $ref
和$id
元数据属性。 默认情况下,它会消耗这些,这意味着它们对您的类是不可见的。 但是,如果将此设置设置为“ Ignore
,则Json.Net根本不会处理元数据属性,从而允许您正常处理它们。 您不需要事先手动操作JSON字符串。
string json = @"
{
""$type"": ""Things.YourThings.YourThingName, Things"",
""Name"": ""Doe""
}";
JsonSerializerSettings settings = new JsonSerializerSettings
{
MetadataPropertyHandling = MetadataPropertyHandling.Ignore
};
CustomName cn = JsonConvert.DeserializeObject<CustomName>(json, settings);
Console.WriteLine("Type: " + cn.Type); // Things.YourThings.YourThingName, Things
Console.WriteLine("Name: " + cn.Name); // Doe
从那里你可以提取这样的短类型名称:
int i = cn.Type.LastIndexOf(", ");
int j = cn.Type.LastIndexOf(".", i);
string shortTypeName = cn.Type.Substring(j + 1, i - j - 1);
Console.WriteLine(shortTypeName); // YourThingName
这个问题有另一个(愚蠢的)解决方案。 创建与$type
属性中描述的相同类型并反序列化到它:
// Put this in a library project called "Things"
namespace Things.YourThings
{
public class YourThingName
{
public string Name { get; set; }
}
}
别的地方:
var customName = JsonConvert.DeserializeObject<Things.YourThings.YourThingName>(jsonText);
var type = customName.GetType().Name;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.