简体   繁体   English

如何用$符号获取Json变量

[英]How to get Json variable with $ symbol

I've been pulling my hair to get the $type variable. 我一直在拉我的头发来获取$type变量。

jsonTxt.json jsonTxt.json

{
  "$type": "Things.YourThings.YourThingName, Things",
  "Name": "Doe"      
}

I tried to get the variable as a string , but with no success. 我试图将变量作为string ,但没有成功。 I just get null . 我得到null

Here is what I do: 这是我做的:

public class CustomName
{

  [JsonProperty("$type")]
  public string Type { get; set; }
  public string Name { get; set; }
}

Then, 然后,

var customName = JsonConvert.DeserializeObject<CustomName>(jsonText);

In actual fact, I just want to extract the type which is just the name YourThingName . 实际上,我只想提取名称为YourThingName的类型。

Try this: 试试这个:

JObject obj = JObject.Parse(jsonText);
var customName = new CustomName()
{
    Name = obj["Name"].ToString(),
    Type = obj["$type"].ToString()
};

Then to get just the YourThingName you can either use a Regex or just String.Split : 然后要获得YourThingName您可以使用正则表达式或只使用String.Split

string name = Regex.Match(customName.Type, @"(?:\.)(\w*)(?:,)").Groups[1].ToString();

Or 要么

string name = customName.Type.Split(',')[0].Split('.')[2];

You must do your boundary checks before accessing the different arrays or you'll end up with IndexOutOfRange exceptions. 您必须在访问不同的阵列之前进行边界检查,否则最终会导致IndexOutOfRange异常。

.Net Fiddle .Net小提琴

Another solution is to replace all occurences of "$type" with something like just "type" . 另一个解决方案是用"$type"的东西替换所有出现的"$type" "type"

jsonText.Replace("\"$type\"", "\"type\"");

With... 随着...

public class CustomName
{
  public string Type { get; set; }
  public string Name { get; set; }
}

...deserialization will work as expected: ...反序列化将按预期工作:

var customName = JsonConvert.DeserializeObject<CustomName>(jsonText);
var type = customName.Type;

Json.Net provides a MetadataPropertyHandling setting which controls how it handles $type , $ref and $id metadata properties in the JSON. Json.Net提供了MetadataPropertyHandling设置,该设置控制它如何处理JSON中的$type$ref$id元数据属性。 By default it will consume these, meaning they are invisible to your classes. 默认情况下,它会消耗这些,这意味着它们对您的类是不可见的。 However, if you set this setting to Ignore , then Json.Net will not process metadata properties at all, allowing you to handle them normally. 但是,如果将此设置设置为“ Ignore ,则Json.Net根本不会处理元数据属性,从而允许您正常处理它们。 You don't need to resort to manipulating the JSON string manually beforehand. 您不需要事先手动操作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

From there you can extract the short type name like this: 从那里你可以提取这样的短类型名称:

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

There is another (stupid) solution to this problem. 这个问题有另一个(愚蠢的)解决方案。 Create the same type as described in the $type property and deserialize to it: 创建与$type属性中描述的相同类型并反序列化到它:

// Put this in a library project called "Things"
namespace Things.YourThings
{
     public class YourThingName
     {
         public string Name { get; set; }
     }
}

Somewhere else: 别的地方:

var customName = JsonConvert.DeserializeObject<Things.YourThings.YourThingName>(jsonText);
var type = customName.GetType().Name;

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

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