簡體   English   中英

如何用$符號獲取Json變量

[英]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異常。

.Net小提琴

另一個解決方案是用"$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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM